
if (typeof UWA == "undefined") var UWA = {};

var NV_HOST = 'www.netvibes.com';
var NV_PATH = 'http://www.netvibes.com/';
var NV_STATIC = '';
var NV_MODULES = 'nvmodules.netvibes.com';


//MooTools, My Object Oriented Javascript Tools. Copyright (c) 2006 Valerio Proietti, <http://mad4milk.net>, MIT Style License.

var MooTools = {
	version: '1.11'
};

function $defined(obj){
	return (obj != undefined);
};

function $type(obj){
	if (!$defined(obj)) return false;
	if (obj.htmlElement) return 'element';
	var type = typeof obj;
	if (type == 'object' && obj.nodeName){
		switch(obj.nodeType){
			case 1: return 'element';
			case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
		}
	}
	if (type == 'object' || type == 'function'){
		switch(obj.constructor){
			case Array: return 'array';
			case RegExp: return 'regexp';
			case Class: return 'class';
		}
		if (typeof obj.length == 'number'){
			if (obj.item) return 'collection';
			if (obj.callee) return 'arguments';
		}
	}
	return type;
};

function $merge(){
	var mix = {};
	for (var i = 0; i < arguments.length; i++){
		for (var property in arguments[i]){
			var ap = arguments[i][property];
			var mp = mix[property];
			if (mp && $type(ap) == 'object' && $type(mp) == 'object') mix[property] = $merge(mp, ap);
			else mix[property] = ap;
		}
	}
	return mix;
};

var $extend = function(){
	var args = arguments;
	if (!args[1]) args = [this, args[0]];
	for (var property in args[1]) args[0][property] = args[1][property];
	return args[0];
};

var $native = function(){
	for (var i = 0, l = arguments.length; i < l; i++){
		arguments[i].extend = function(props){
			for (var prop in props){
				if (!this.prototype[prop]) this.prototype[prop] = props[prop];
				if (!this[prop]) this[prop] = $native.generic(prop);
			}
		};
	}
};

$native.generic = function(prop){
	return function(bind){
		return this.prototype[prop].apply(bind, Array.prototype.slice.call(arguments, 1));
	};
};

$native(Function, Array, String, Number);

function $chk(obj){
	return !!(obj || obj === 0);
};

function $pick(obj, picked){
	return $defined(obj) ? obj : picked;
};

function $random(min, max){
	return Math.floor(Math.random() * (max - min + 1) + min);
};

function $time(){
	return new Date().getTime();
};

function $clear(timer){
	clearTimeout(timer);
	clearInterval(timer);
	return null;
};

var Abstract = function(obj){
	obj = obj || {};
	obj.extend = $extend;
	return obj;
};

var Window = new Abstract(window);
var Document = new Abstract(document);
document.head = document.getElementsByTagName('head')[0];

window.xpath = !!(document.evaluate);
if (window.ActiveXObject) window.ie = window[window.XMLHttpRequest ? 'ie7' : 'ie6'] = true;
else if (document.childNodes && !document.all && !navigator.taintEnabled) window.webkit = window[window.xpath ? 'webkit420' : 'webkit419'] = true;
else if (document.getBoxObjectFor != null) window.gecko = true;

window.khtml = window.webkit;

Object.extend = $extend;

if (typeof HTMLElement == 'undefined'){
	var HTMLElement = function(){};
	if (window.webkit) document.createElement("iframe");
	HTMLElement.prototype = (window.webkit) ? window["[[DOMElement.prototype]]"] : {};
}
HTMLElement.prototype.htmlElement = function(){};

if (window.ie6) try {document.execCommand("BackgroundImageCache", false, true);} catch(e){};

var Class = function(properties){
	var klass = function(){
		return (arguments[0] !== null && this.initialize && $type(this.initialize) == 'function') ? this.initialize.apply(this, arguments) : this;
	};
	$extend(klass, this);
	klass.prototype = properties;
	klass.constructor = Class;
	return klass;
};

Class.empty = function(){};

Class.prototype = {

	extend: function(properties){
		var proto = new this(null);
		for (var property in properties){
			var pp = proto[property];
			proto[property] = Class.Merge(pp, properties[property]);
		}
		return new Class(proto);
	},

	implement: function(){
		for (var i = 0, l = arguments.length; i < l; i++) $extend(this.prototype, arguments[i]);
	}

};

Class.Merge = function(previous, current){
	if (previous && previous != current){
		var type = $type(current);
		if (type != $type(previous)) return current;
		switch(type){
			case 'function':
				var merged = function(){
					this.parent = arguments.callee.parent;
					return current.apply(this, arguments);
				};
				merged.parent = previous;
				return merged;
			case 'object': return $merge(previous, current);
		}
	}
	return current;
};

var Chain = new Class({

	chain: function(fn){
		this.chains = this.chains || [];
		this.chains.push(fn);
		return this;
	},

	callChain: function(){
		if (this.chains && this.chains.length) this.chains.shift().delay(10, this);
	},

	clearChain: function(){
		this.chains = [];
	}

});

var Events = new Class({

	addEvent: function(type, fn){
		if (fn != Class.empty){
			this.$events = this.$events || {};
			this.$events[type] = this.$events[type] || [];
			this.$events[type].include(fn);
		}
		return this;
	},

	fireEvent: function(type, args, delay){
		if (this.$events && this.$events[type]){
			this.$events[type].each(function(fn){
				fn.create({'bind': this, 'delay': delay, 'arguments': args})();
			}, this);
		}
		return this;
	},

	removeEvent: function(type, fn){
		if (this.$events && this.$events[type]) this.$events[type].remove(fn);
		return this;
	}

});

var Options = new Class({

	setOptions: function(){
		this.options = $merge.apply(null, [this.options].extend(arguments));
		if (this.addEvent){
			for (var option in this.options){
				if ($type(this.options[option] == 'function') && (/^on[A-Z]/).test(option)) this.addEvent(option, this.options[option]);
			}
		}
		return this;
	}

});

Array.extend({

	forEach: function(fn, bind){
		for (var i = 0, j = this.length; i < j; i++) fn.call(bind, this[i], i, this);
	},

	filter: function(fn, bind){
		var results = [];
		for (var i = 0, j = this.length; i < j; i++){
			if (fn.call(bind, this[i], i, this)) results.push(this[i]);
		}
		return results;
	},

	map: function(fn, bind){
		var results = [];
		for (var i = 0, j = this.length; i < j; i++) results[i] = fn.call(bind, this[i], i, this);
		return results;
	},

	every: function(fn, bind){
		for (var i = 0, j = this.length; i < j; i++){
			if (!fn.call(bind, this[i], i, this)) return false;
		}
		return true;
	},

	some: function(fn, bind){
		for (var i = 0, j = this.length; i < j; i++){
			if (fn.call(bind, this[i], i, this)) return true;
		}
		return false;
	},

	indexOf: function(item, from){
		var len = this.length;
		for (var i = (from < 0) ? Math.max(0, len + from) : from || 0; i < len; i++){
			if (this[i] === item) return i;
		}
		return -1;
	},

	copy: function(start, length){
		start = start || 0;
		if (start < 0) start = this.length + start;
		length = length || (this.length - start);
		var newArray = [];
		for (var i = 0; i < length; i++) newArray[i] = this[start++];
		return newArray;
	},

	remove: function(item){
		var i = 0;
		var len = this.length;
		while (i < len){
			if (this[i] === item){
				this.splice(i, 1);
				len--;
			} else {
				i++;
			}
		}
		return this;
	},

	contains: function(item, from){
		return this.indexOf(item, from) != -1;
	},

	associate: function(keys){
		var obj = {}, length = Math.min(this.length, keys.length);
		for (var i = 0; i < length; i++) obj[keys[i]] = this[i];
		return obj;
	},

	extend: function(array){
		for (var i = 0, j = array.length; i < j; i++) this.push(array[i]);
		return this;
	},

	merge: function(array){
		for (var i = 0, l = array.length; i < l; i++) this.include(array[i]);
		return this;
	},

	include: function(item){
		if (!this.contains(item)) this.push(item);
		return this;
	},

	getRandom: function(){
		return this[$random(0, this.length - 1)] || null;
	},

	getLast: function(){
		return this[this.length - 1] || null;
	}

});

Array.prototype.each = Array.prototype.forEach;
Array.each = Array.forEach;

function $A(array){
	return Array.copy(array);
};

function $each(iterable, fn, bind){
	if (iterable && typeof iterable.length == 'number' && $type(iterable) != 'object'){
		Array.forEach(iterable, fn, bind);
	} else {
		 for (var name in iterable) fn.call(bind || iterable, iterable[name], name);
	}
};

Array.prototype.test = Array.prototype.contains;

String.extend({

	test: function(regex, params){
		return (($type(regex) == 'string') ? new RegExp(regex, params) : regex).test(this);
	},

	toInt: function(){
		return parseInt(this, 10);
	},

	toFloat: function(){
		return parseFloat(this);
	},

	camelCase: function(){
		return this.replace(/-\D/g, function(match){
			return match.charAt(1).toUpperCase();
		});
	},

	hyphenate: function(){
		return this.replace(/\w[A-Z]/g, function(match){
			return (match.charAt(0) + '-' + match.charAt(1).toLowerCase());
		});
	},

	capitalize: function(){
		return this.replace(/\b[a-z]/g, function(match){
			return match.toUpperCase();
		});
	},

	trim: function(){
		return this.replace(/^\s+|\s+$/g, '');
	},

	clean: function(){
		return this.replace(/\s{2,}/g, ' ').trim();
	},

	rgbToHex: function(array){
		var rgb = this.match(/\d{1,3}/g);
		return (rgb) ? rgb.rgbToHex(array) : false;
	},

	hexToRgb: function(array){
		var hex = this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
		return (hex) ? hex.slice(1).hexToRgb(array) : false;
	},

	contains: function(string, s){
		return (s) ? (s + this + s).indexOf(s + string + s) > -1 : this.indexOf(string) > -1;
	},

	escapeRegExp: function(){
		return this.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
	}

});

Array.extend({

	rgbToHex: function(array){
		if (this.length < 3) return false;
		if (this.length == 4 && this[3] == 0 && !array) return 'transparent';
		var hex = [];
		for (var i = 0; i < 3; i++){
			var bit = (this[i] - 0).toString(16);
			hex.push((bit.length == 1) ? '0' + bit : bit);
		}
		return array ? hex : '#' + hex.join('');
	},

	hexToRgb: function(array){
		if (this.length != 3) return false;
		var rgb = [];
		for (var i = 0; i < 3; i++){
			rgb.push(parseInt((this[i].length == 1) ? this[i] + this[i] : this[i], 16));
		}
		return array ? rgb : 'rgb(' + rgb.join(',') + ')';
	}

});

Function.extend({

	create: function(options){
		var fn = this;
		options = $merge({
			'bind': fn,
			'event': false,
			'arguments': null,
			'delay': false,
			'periodical': false,
			'attempt': false
		}, options);
		if ($chk(options.arguments) && $type(options.arguments) != 'array') options.arguments = [options.arguments];
		return function(event){
			var args;
			if (options.event){
				event = event || window.event;
				args = [(options.event === true) ? event : new options.event(event)];
				if (options.arguments) args.extend(options.arguments);
			}
			else args = options.arguments || arguments;
			var returns = function(){
				return fn.apply($pick(options.bind, fn), args);
			};
			if (options.delay) return setTimeout(returns, options.delay);
			if (options.periodical) return setInterval(returns, options.periodical);
			if (options.attempt) try {return returns();} catch(err){return false;};
			return returns();
		};
	},

	pass: function(args, bind){
		return this.create({'arguments': args, 'bind': bind});
	},

	attempt: function(args, bind){
		return this.create({'arguments': args, 'bind': bind, 'attempt': true})();
	},

	bind: function(bind, args){
		return this.create({'bind': bind, 'arguments': args});
	},

	bindAsEventListener: function(bind, args){
		return this.create({'bind': bind, 'event': true, 'arguments': args});
	},

	delay: function(delay, bind, args){
		return this.create({'delay': delay, 'bind': bind, 'arguments': args})();
	},

	periodical: function(interval, bind, args){
		return this.create({'periodical': interval, 'bind': bind, 'arguments': args})();
	}

});

Number.extend({

	toInt: function(){
		return parseInt(this);
	},

	toFloat: function(){
		return parseFloat(this);
	},

	limit: function(min, max){
		return Math.min(max, Math.max(min, this));
	},

	round: function(precision){
		precision = Math.pow(10, precision || 0);
		return Math.round(this * precision) / precision;
	},

	times: function(fn){
		for (var i = 0; i < this; i++) fn(i);
	}

});

var Element = new Class({

	initialize: function(el, props){
		if ($type(el) == 'string'){
			if (window.ie && props && (props.name || props.type)){
				var name = (props.name) ? ' name="' + props.name + '"' : '';
				var type = (props.type) ? ' type="' + props.type + '"' : '';
				delete props.name;
				delete props.type;
				el = '<' + el + name + type + '>';
			}
			el = document.createElement(el);
		}
		el = $(el);
		return (!props || !el) ? el : el.set(props);
	}

});

var Elements = new Class({

	initialize: function(elements){
		return (elements) ? $extend(elements, this) : this;
	}

});

Elements.extend = function(props){
	for (var prop in props){
		this.prototype[prop] = props[prop];
		this[prop] = $native.generic(prop);
	}
};

function $(el){
	if (!el) return null;
	if (el.htmlElement) return Garbage.collect(el);
	if ([window, document].contains(el)) return el;
	var type = $type(el);
	if (type == 'string'){
		el = document.getElementById(el);
		type = (el) ? 'element' : false;
	}
	if (type != 'element') return null;
	if (el.htmlElement) return Garbage.collect(el);
	if (['object', 'embed'].contains(el.tagName.toLowerCase())) return el;
	$extend(el, Element.prototype);
	el.htmlElement = function(){};
	return Garbage.collect(el);
};

document.getElementsBySelector = document.getElementsByTagName;

function $$(){
	var elements = [];
	for (var i = 0, j = arguments.length; i < j; i++){
		var selector = arguments[i];
		switch($type(selector)){
			case 'element': elements.push(selector);
			case 'boolean': break;
			case false: break;
			case 'string': selector = document.getElementsBySelector(selector, true);
			default: elements.extend(selector);
		}
	}
	return $$.unique(elements);
};

$$.unique = function(array){
	var elements = [];
	for (var i = 0, l = array.length; i < l; i++){
		if (array[i].$included) continue;
		var element = $(array[i]);
		if (element && !element.$included){
			element.$included = true;
			elements.push(element);
		}
	}
	for (var n = 0, d = elements.length; n < d; n++) elements[n].$included = null;
	return new Elements(elements);
};

Elements.Multi = function(property){
	return function(){
		var args = arguments;
		var items = [];
		var elements = true;
		for (var i = 0, j = this.length, returns; i < j; i++){
			returns = this[i][property].apply(this[i], args);
			if ($type(returns) != 'element') elements = false;
			items.push(returns);
		};
		return (elements) ? $$.unique(items) : items;
	};
};

Element.extend = function(properties){
	for (var property in properties){
		HTMLElement.prototype[property] = properties[property];
		Element.prototype[property] = properties[property];
		Element[property] = $native.generic(property);
		var elementsProperty = (Array.prototype[property]) ? property + 'Elements' : property;
		Elements.prototype[elementsProperty] = Elements.Multi(property);
	}
};

Element.extend({

	set: function(props){
		for (var prop in props){
			var val = props[prop];
			switch(prop){
				case 'styles': this.setStyles(val); break;
				case 'events': if (this.addEvents) this.addEvents(val); break;
				case 'properties': this.setProperties(val); break;
				default: this.setProperty(prop, val);
			}
		}
		return this;
	},

	inject: function(el, where){
		el = $(el);
		switch(where){
			case 'before': el.parentNode.insertBefore(this, el); break;
			case 'after':
				var next = el.getNext();
				if (!next) el.parentNode.appendChild(this);
				else el.parentNode.insertBefore(this, next);
				break;
			case 'top':
				var first = el.firstChild;
				if (first){
					el.insertBefore(this, first);
					break;
				}
			default: el.appendChild(this);
		}
		return this;
	},

	injectBefore: function(el){
		return this.inject(el, 'before');
	},

	injectAfter: function(el){
		return this.inject(el, 'after');
	},

	injectInside: function(el){
		return this.inject(el, 'bottom');
	},

	injectTop: function(el){
		return this.inject(el, 'top');
	},

	adopt: function(){
		var elements = [];
		$each(arguments, function(argument){
			elements = elements.concat(argument);
		});
		$$(elements).inject(this);
		return this;
	},

	remove: function(){
		return this.parentNode.removeChild(this);
	},

	clone: function(contents){
		var el = $(this.cloneNode(contents !== false));
		if (!el.$events) return el;
		el.$events = {};
		for (var type in this.$events) el.$events[type] = {
			'keys': $A(this.$events[type].keys),
			'values': $A(this.$events[type].values)
		};
		return el.removeEvents();
	},

	replaceWith: function(el){
		el = $(el);
		this.parentNode.replaceChild(el, this);
		return el;
	},

	appendText: function(text){
		this.appendChild(document.createTextNode(text));
		return this;
	},

	hasClass: function(className){
		return this.className.contains(className, ' ');
	},

	addClass: function(className){
		if (!this.hasClass(className)) this.className = (this.className + ' ' + className).clean();
		return this;
	},

	removeClass: function(className){
		this.className = this.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1').clean();
		return this;
	},

	toggleClass: function(className){
		return this.hasClass(className) ? this.removeClass(className) : this.addClass(className);
	},

	setStyle: function(property, value){
		switch(property){
			case 'opacity': return this.setOpacity(parseFloat(value));
			case 'float': property = (window.ie) ? 'styleFloat' : 'cssFloat';
		}
		property = property.camelCase();
		switch($type(value)){
			case 'number': if (!['zIndex', 'zoom'].contains(property)) value += 'px'; break;
			case 'array': value = 'rgb(' + value.join(',') + ')';
		}
		try {
			this.style[property] = value;
		} catch (e) {
			
		}
		return this;
	},

	setStyles: function(source){
		switch($type(source)){
			case 'object': Element.setMany(this, 'setStyle', source); break;
			case 'string': this.style.cssText = source;
		}
		return this;
	},

	setOpacity: function(opacity){
		if (opacity == 0){
			if (this.style.visibility != "hidden") this.style.visibility = "hidden";
		} else {
			if (this.style.visibility != "visible") this.style.visibility = "visible";
		}
		if (!this.currentStyle || !this.currentStyle.hasLayout) this.style.zoom = 1;
		if (window.ie) this.style.filter = (opacity == 1) ? '' : "alpha(opacity=" + opacity * 100 + ")";
		this.style.opacity = this.$tmp.opacity = opacity;
		return this;
	},

	getStyle: function(property){
		property = property.camelCase();
		var result = this.style[property];
		if (!$chk(result)){
			if (property == 'opacity') return this.$tmp.opacity;
			result = [];
			for (var style in Element.Styles){
				if (property == style){
					Element.Styles[style].each(function(s){
						var style = this.getStyle(s);
						result.push(parseInt(style) ? style : '0px');
					}, this);
					if (property == 'border'){
						var every = result.every(function(bit){
							return (bit == result[0]);
						});
						return (every) ? result[0] : false;
					}
					return result.join(' ');
				}
			}
			if (property.contains('border')){
				if (Element.Styles.border.contains(property)){
					return ['Width', 'Style', 'Color'].map(function(p){
						return this.getStyle(property + p);
					}, this).join(' ');
				} else if (Element.borderShort.contains(property)){
					return ['Top', 'Right', 'Bottom', 'Left'].map(function(p){
						return this.getStyle('border' + p + property.replace('border', ''));
					}, this).join(' ');
				}
			}
			if (document.defaultView) result = document.defaultView.getComputedStyle(this, null).getPropertyValue(property.hyphenate());
			else if (this.currentStyle) result = this.currentStyle[property];
		}
		if (window.ie) result = Element.fixStyle(property, result, this);
		if (result && property.test(/color/i) && result.contains('rgb')){
			return result.split('rgb').splice(1,4).map(function(color){
				return color.rgbToHex();
			}).join(' ');
		}
		return result;
	},

	getStyles: function(){
		return Element.getMany(this, 'getStyle', arguments);
	},

	walk: function(brother, start){
		brother += 'Sibling';
		var el = (start) ? this[start] : this[brother];
		while (el && $type(el) != 'element') el = el[brother];
		return $(el);
	},

	getPrevious: function(){
		return this.walk('previous');
	},

	getNext: function(){
		return this.walk('next');
	},

	getFirst: function(){
		return this.walk('next', 'firstChild');
	},

	getLast: function(){
		return this.walk('previous', 'lastChild');
	},

	getParent: function(){
		return $(this.parentNode);
	},

	getChildren: function(){
		return $$(this.childNodes);
	},

	hasChild: function(el){
		return !!$A(this.getElementsByTagName('*')).contains(el);
	},

	getProperty: function(property){
		var index = Element.Properties[property];
		if (index) return this[index];
		var flag = Element.PropertiesIFlag[property] || 0;
		if (!window.ie || flag) return this.getAttribute(property, flag);
		var node = this.attributes[property];
		return (node) ? node.nodeValue : null;
	},

	removeProperty: function(property){
		var index = Element.Properties[property];
		if (index) this[index] = '';
		else this.removeAttribute(property);
		return this;
	},

	getProperties: function(){
		return Element.getMany(this, 'getProperty', arguments);
	},

	setProperty: function(property, value){
		var index = Element.Properties[property];
		if (index) this[index] = value;
		else this.setAttribute(property, value);
		return this;
	},

	setProperties: function(source){
		return Element.setMany(this, 'setProperty', source);
	},

	setHTML: function(){
		this.innerHTML = $A(arguments).join('');
		return this;
	},

	setText: function(text){
		var tag = this.getTag();
		if (['style', 'script'].contains(tag)){
			if (window.ie){
				if (tag == 'style') this.styleSheet.cssText = text;
				else if (tag ==  'script') this.setProperty('text', text);
				return this;
			} else {
				this.removeChild(this.firstChild);
				return this.appendText(text);
			}
		}
		this[$defined(this.innerText) ? 'innerText' : 'textContent'] = text;
		return this;
	},

	getText: function(){
		var tag = this.getTag();
		if (['style', 'script'].contains(tag)){
			if (window.ie){
				if (tag == 'style') return this.styleSheet.cssText;
				else if (tag ==  'script') return this.getProperty('text');
			} else {
				return this.innerHTML;
			}
		}
		return ($pick(this.innerText, this.textContent));
	},

	getTag: function(){
		return this.tagName.toLowerCase();
	},

	empty: function(){
		Garbage.trash(this.getElementsByTagName('*'));
		return this.setHTML('');
	}

});

Element.fixStyle = function(property, result, element){
	if ($chk(parseInt(result))) return result;
	if (['height', 'width'].contains(property)){
		var values = (property == 'width') ? ['left', 'right'] : ['top', 'bottom'];
		var size = 0;
		values.each(function(value){
			size += element.getStyle('border-' + value + '-width').toInt() + element.getStyle('padding-' + value).toInt();
		});
		return element['offset' + property.capitalize()] - size + 'px';
	} else if (property.test(/border(.+)Width|margin|padding/)){
		return '0px';
	}
	return result;
};

Element.Styles = {'border': [], 'padding': [], 'margin': []};
['Top', 'Right', 'Bottom', 'Left'].each(function(direction){
	for (var style in Element.Styles) Element.Styles[style].push(style + direction);
});

Element.borderShort = ['borderWidth', 'borderStyle', 'borderColor'];

Element.getMany = function(el, method, keys){
	var result = {};
	$each(keys, function(key){
		result[key] = el[method](key);
	});
	return result;
};

Element.setMany = function(el, method, pairs){
	for (var key in pairs) el[method](key, pairs[key]);
	return el;
};

Element.Properties = new Abstract({
	'class': 'className', 'for': 'htmlFor', 'colspan': 'colSpan', 'rowspan': 'rowSpan',
	'accesskey': 'accessKey', 'tabindex': 'tabIndex', 'maxlength': 'maxLength',
	'readonly': 'readOnly', 'frameborder': 'frameBorder', 'value': 'value',
	'disabled': 'disabled', 'checked': 'checked', 'multiple': 'multiple', 'selected': 'selected'
});
Element.PropertiesIFlag = {
	'href': 2, 'src': 2
};

Element.Methods = {
	Listeners: {
		addListener: function(type, fn){
			if (this.addEventListener) this.addEventListener(type, fn, false);
			else this.attachEvent('on' + type, fn);
			return this;
		},

		removeListener: function(type, fn){
			if (this.removeEventListener) this.removeEventListener(type, fn, false);
			else this.detachEvent('on' + type, fn);
			return this;
		}
	}
};

window.extend(Element.Methods.Listeners);
document.extend(Element.Methods.Listeners);
Element.extend(Element.Methods.Listeners);

var Garbage = {

	elements: [],

	collect: function(el){
		if (!el.$tmp){
			Garbage.elements.push(el);
			el.$tmp = {'opacity': 1};
		}
		return el;
	},

	trash: function(elements, unload){
		for (var i = 0, j = elements.length, el; i < j; i++){
			if (!(el = elements[i]) || !el.$tmp) continue;
			if (el.$events) el.fireEvent('trash', [!!(unload)]).removeEvents();
			for (var p in el.$tmp) el.$tmp[p] = null;
			for (var d in Element.prototype) el[d] = null;
			if (!unload) Garbage.elements[Garbage.elements.indexOf(el)] = null;
			el.htmlElement = el.$tmp = el = null;
		}
		if (!unload) Garbage.elements.remove(null);
	},

	empty: function(){
		Garbage.collect(window);
		Garbage.collect(document);
		Garbage.trash(Garbage.elements, true);
	}

};

window.addListener('beforeunload', function(){
	window.addListener('unload', Garbage.empty);
	if (window.ie) window.addListener('unload', CollectGarbage);
});

var Event = new Class({

	initialize: function(event){
		if (event && event.$extended) return event;
		this.$extended = true;
		event = event || window.event;
		this.event = event;
		this.type = event.type;
		this.target = event.target || event.srcElement;
		if (this.target.nodeType == 3) this.target = this.target.parentNode;
		this.shift = event.shiftKey;
		this.control = event.ctrlKey;
		this.alt = event.altKey;
		this.meta = event.metaKey;
		if (['DOMMouseScroll', 'mousewheel'].contains(this.type)){
			this.wheel = (event.wheelDelta) ? event.wheelDelta / 120 : -(event.detail || 0) / 3;
		} else if (this.type.contains('key')){
			this.code = event.which || event.keyCode;
			for (var name in Event.keys){
				if (Event.keys[name] == this.code){
					this.key = name;
					break;
				}
			}
			if (this.type == 'keydown' || event.keyCode > 0){
				var fKey = this.code - 111;
				if (fKey > 0 && fKey < 13) this.key = 'f' + fKey;
			}
			this.key = this.key || String.fromCharCode(this.code).toLowerCase();
		} else if (this.type.test(/(click|mouse|menu)/)){
			this.page = {
				'x': event.pageX || event.clientX + document.documentElement.scrollLeft,
				'y': event.pageY || event.clientY + document.documentElement.scrollTop
			};
			this.client = {
				'x': event.pageX ? event.pageX - window.pageXOffset : event.clientX,
				'y': event.pageY ? event.pageY - window.pageYOffset : event.clientY
			};
			this.rightClick = (event.which == 3) || (event.button == 2);
			switch(this.type){
				case 'mouseover': this.relatedTarget = event.relatedTarget || event.fromElement; break;
				case 'mouseout': this.relatedTarget = event.relatedTarget || event.toElement;
			}
			this.fixRelatedTarget();
		}
		return this;
	},

	stop: function(){
		return this.stopPropagation().preventDefault();
	},

	stopPropagation: function(){
		if (this.event.stopPropagation) this.event.stopPropagation();
		else this.event.cancelBubble = true;
		return this;
	},

	preventDefault: function(){
		if (this.event.preventDefault) this.event.preventDefault();
		else this.event.returnValue = false;
		return this;
	}

});

Event.fix = {

	relatedTarget: function(){
		if (this.relatedTarget && this.relatedTarget.nodeType == 3) this.relatedTarget = this.relatedTarget.parentNode;
	},

	relatedTargetGecko: function(){
		try {Event.fix.relatedTarget.call(this);} catch(e){this.relatedTarget = this.target;}
	}

};

Event.prototype.fixRelatedTarget = (window.gecko) ? Event.fix.relatedTargetGecko : Event.fix.relatedTarget;

Event.keys = new Abstract({
	'enter': 13,
	'up': 38,
	'down': 40,
	'left': 37,
	'right': 39,
	'esc': 27,
	'space': 32,
	'backspace': 8,
	'tab': 9,
	'delete': 46
});

Element.Methods.Events = {

	addEvent: function(type, fn){
		this.$events = this.$events || {};
		this.$events[type] = this.$events[type] || {'keys': [], 'values': []};
		if (this.$events[type].keys.contains(fn)) return this;
		this.$events[type].keys.push(fn);
		var realType = type;
		var custom = Element.Events[type];
		if (custom){
			if (custom.add) custom.add.call(this, fn);
			if (custom.map) fn = custom.map;
			if (custom.type) realType = custom.type;
		}
		if (!this.addEventListener) fn = fn.create({'bind': this, 'event': true});
		this.$events[type].values.push(fn);
		return (Element.NativeEvents.contains(realType)) ? this.addListener(realType, fn) : this;
	},

	removeEvent: function(type, fn){
		if (!this.$events || !this.$events[type]) return this;
		var pos = this.$events[type].keys.indexOf(fn);
		if (pos == -1) return this;
		var key = this.$events[type].keys.splice(pos,1)[0];
		var value = this.$events[type].values.splice(pos,1)[0];
		var custom = Element.Events[type];
		if (custom){
			if (custom.remove) custom.remove.call(this, fn);
			if (custom.type) type = custom.type;
		}
		return (Element.NativeEvents.contains(type)) ? this.removeListener(type, value) : this;
	},

	addEvents: function(source){
		return Element.setMany(this, 'addEvent', source);
	},

	removeEvents: function(type){
		if (!this.$events) return this;
		if (!type){
			for (var evType in this.$events) this.removeEvents(evType);
			this.$events = null;
		} else if (this.$events[type]){
			this.$events[type].keys.each(function(fn){
				this.removeEvent(type, fn);
			}, this);
			this.$events[type] = null;
		}
		return this;
	},

	fireEvent: function(type, args, delay){
		if (this.$events && this.$events[type]){
			this.$events[type].keys.each(function(fn){
				fn.create({'bind': this, 'delay': delay, 'arguments': args})();
			}, this);
		}
		return this;
	},

	cloneEvents: function(from, type){
		if (!from.$events) return this;
		if (!type){
			for (var evType in from.$events) this.cloneEvents(from, evType);
		} else if (from.$events[type]){
			from.$events[type].keys.each(function(fn){
				this.addEvent(type, fn);
			}, this);
		}
		return this;
	}

};

window.extend(Element.Methods.Events);
document.extend(Element.Methods.Events);
Element.extend(Element.Methods.Events);

Element.Events = new Abstract({

	'mouseenter': {
		type: 'mouseover',
		map: function(event){
			event = new Event(event);
			if (event.relatedTarget != this && !this.hasChild(event.relatedTarget)) this.fireEvent('mouseenter', event);
		}
	},

	'mouseleave': {
		type: 'mouseout',
		map: function(event){
			event = new Event(event);
			if (event.relatedTarget != this && !this.hasChild(event.relatedTarget)) this.fireEvent('mouseleave', event);
		}
	},

	'mousewheel': {
		type: (window.gecko) ? 'DOMMouseScroll' : 'mousewheel'
	}

});

Element.NativeEvents = [
	'click', 'dblclick', 'mouseup', 'mousedown',
	'mousewheel', 'DOMMouseScroll',
	'mouseover', 'mouseout', 'mousemove',
	'keydown', 'keypress', 'keyup',
	'load', 'unload', 'beforeunload', 'resize', 'move',
	'focus', 'blur', 'change', 'submit', 'reset', 'select',
	'error', 'abort', 'contextmenu', 'scroll'
];

Function.extend({

	bindWithEvent: function(bind, args){
		return this.create({'bind': bind, 'arguments': args, 'event': Event});
	}

});

Elements.extend({

	filterByTag: function(tag){
		return new Elements(this.filter(function(el){
			return (Element.getTag(el) == tag);
		}));
	},

	filterByClass: function(className, nocash){
		var elements = this.filter(function(el){
			return (el.className && el.className.contains(className, ' '));
		});
		return (nocash) ? elements : new Elements(elements);
	},

	filterById: function(id, nocash){
		var elements = this.filter(function(el){
			return (el.id == id);
		});
		return (nocash) ? elements : new Elements(elements);
	},

	filterByAttribute: function(name, operator, value, nocash){
		var elements = this.filter(function(el){
			var current = Element.getProperty(el, name);
			if (!current) return false;
			if (!operator) return true;
			switch(operator){
				case '=': return (current == value);
				case '*=': return (current.contains(value));
				case '^=': return (current.substr(0, value.length) == value);
				case '$=': return (current.substr(current.length - value.length) == value);
				case '!=': return (current != value);
				case '~=': return current.contains(value, ' ');
			}
			return false;
		});
		return (nocash) ? elements : new Elements(elements);
	}

});

function $E(selector, filter){
	return ($(filter) || document).getElement(selector);
};

function $ES(selector, filter){
	return ($(filter) || document).getElementsBySelector(selector);
};

$$.shared = {

	'regexp': /^(\w*|\*)(?:#([\w-]+)|\.([\w-]+))?(?:\[(\w+)(?:([!*^$]?=)["']?([^"'\]]*)["']?)?])?$/,

	'xpath': {

		getParam: function(items, context, param, i){
			var temp = [context.namespaceURI ? 'xhtml:' : '', param[1]];
			if (param[2]) temp.push('[@id="', param[2], '"]');
			if (param[3]) temp.push('[contains(concat(" ", @class, " "), " ', param[3], ' ")]');
			if (param[4]){
				if (param[5] && param[6]){
					switch(param[5]){
						case '*=': temp.push('[contains(@', param[4], ', "', param[6], '")]'); break;
						case '^=': temp.push('[starts-with(@', param[4], ', "', param[6], '")]'); break;
						case '$=': temp.push('[substring(@', param[4], ', string-length(@', param[4], ') - ', param[6].length, ' + 1) = "', param[6], '"]'); break;
						case '=': temp.push('[@', param[4], '="', param[6], '"]'); break;
						case '!=': temp.push('[@', param[4], '!="', param[6], '"]');
					}
				} else {
					temp.push('[@', param[4], ']');
				}
			}
			items.push(temp.join(''));
			return items;
		},

		getItems: function(items, context, nocash){
			var elements = [];
			var xpath = document.evaluate('.//' + items.join('//'), context, $$.shared.resolver, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
			for (var i = 0, j = xpath.snapshotLength; i < j; i++) elements.push(xpath.snapshotItem(i));
			return (nocash) ? elements : new Elements(elements.map($));
		}

	},

	'normal': {

		getParam: function(items, context, param, i){
			if (i == 0){
				if (param[2]){
					var el = context.getElementById(param[2]);
					if (!el || ((param[1] != '*') && (Element.getTag(el) != param[1]))) return false;
					items = [el];
				} else {
					items = $A(context.getElementsByTagName(param[1]));
				}
			} else {
				items = $$.shared.getElementsByTagName(items, param[1]);
				if (param[2]) items = Elements.filterById(items, param[2], true);
			}
			if (param[3]) items = Elements.filterByClass(items, param[3], true);
			if (param[4]) items = Elements.filterByAttribute(items, param[4], param[5], param[6], true);
			return items;
		},

		getItems: function(items, context, nocash){
			return (nocash) ? items : $$.unique(items);
		}

	},

	resolver: function(prefix){
		return (prefix == 'xhtml') ? 'http://www.w3.org/1999/xhtml' : false;
	},

	getElementsByTagName: function(context, tagName){
		var found = [];
		for (var i = 0, j = context.length; i < j; i++) found.extend(context[i].getElementsByTagName(tagName));
		return found;
	}

};

$$.shared.method = (window.xpath) ? 'xpath' : 'normal';

Element.Methods.Dom = {

	getElements: function(selector, nocash){
		var items = [];
		selector = selector.trim().split(' ');
		for (var i = 0, j = selector.length; i < j; i++){
			var sel = selector[i];
			var param = sel.match($$.shared.regexp);
			if (!param) break;
			param[1] = param[1] || '*';
			var temp = $$.shared[$$.shared.method].getParam(items, this, param, i);
			if (!temp) break;
			items = temp;
		}
		return $$.shared[$$.shared.method].getItems(items, this, nocash);
	},

	getElement: function(selector){
		return $(this.getElements(selector, true)[0] || false);
	},

	getElementsBySelector: function(selector, nocash){
		var elements = [];
		selector = selector.split(',');
		for (var i = 0, j = selector.length; i < j; i++) elements = elements.concat(this.getElements(selector[i], true));
		return (nocash) ? elements : $$.unique(elements);
	}

};

Element.extend({

	getElementById: function(id){
		var el = document.getElementById(id);
		if (!el) return false;
		for (var parent = el.parentNode; parent != this; parent = parent.parentNode){
			if (!parent) return false;
		}
		return el;
	}/*compatibility*/,

	getElementsByClassName: function(className){ 
		return this.getElements('.' + className); 
	}

});

document.extend(Element.Methods.Dom);
Element.extend(Element.Methods.Dom);

Element.extend({

	getValue: function(){
		switch(this.getTag()){
			case 'select':
				var values = [];
				$each(this.options, function(option){
					if (option.selected) values.push($pick(option.value, option.text));
				});
				return (this.multiple) ? values : values[0];
			case 'input': if (!(this.checked && ['checkbox', 'radio'].contains(this.type)) && !['hidden', 'text', 'password'].contains(this.type)) break;
			case 'textarea': return this.value;
		}
		return false;
	},

	getFormElements: function(){
		return $$(this.getElementsByTagName('input'), this.getElementsByTagName('select'), this.getElementsByTagName('textarea'));
	},

	toQueryString: function(){
		var queryString = [];
		this.getFormElements().each(function(el){
			var name = el.name;
			var value = el.getValue();
			if (value === false || !name || el.disabled) return;
			var qs = function(val){
				queryString.push(name + '=' + encodeURIComponent(val));
			};
			if ($type(value) == 'array') value.each(qs);
			else qs(value);
		});
		return queryString.join('&');
	}

});

Element.extend({

	scrollTo: function(x, y){
		this.scrollLeft = x;
		this.scrollTop = y;
	},

	getSize: function(){
		return {
			'scroll': {'x': this.scrollLeft, 'y': this.scrollTop},
			'size': {'x': this.offsetWidth, 'y': this.offsetHeight},
			'scrollSize': {'x': this.scrollWidth, 'y': this.scrollHeight}
		};
	},

	getPosition: function(overflown){
		overflown = overflown || [];
		var el = this, left = 0, top = 0;
		do {
			left += el.offsetLeft || 0;
			top += el.offsetTop || 0;
			el = el.offsetParent;
		} while (el);
		overflown.each(function(element){
			left -= element.scrollLeft || 0;
			top -= element.scrollTop || 0;
		});
		return {'x': left, 'y': top};
	},

	getTop: function(overflown){
		return this.getPosition(overflown).y;
	},

	getLeft: function(overflown){
		return this.getPosition(overflown).x;
	},

	getCoordinates: function(overflown){
		var position = this.getPosition(overflown);
		var obj = {
			'width': this.offsetWidth,
			'height': this.offsetHeight,
			'left': position.x,
			'top': position.y
		};
		obj.right = obj.left + obj.width;
		obj.bottom = obj.top + obj.height;
		return obj;
	}

});

Element.Events.domready = {

	add: function(fn){
		if (window.loaded){
			fn.call(this);
			return;
		}
		var domReady = function(){
			if (window.loaded) return;
			window.loaded = true;
			window.timer = $clear(window.timer);
			this.fireEvent('domready');
		}.bind(this);
		if (document.readyState && window.webkit){
			window.timer = function(){
				if (['loaded','complete'].contains(document.readyState)) domReady();
			}.periodical(50);
		} else if (document.readyState && window.ie){
			if (!$('ie_ready')){
				var src = (window.location.protocol == 'https:') ? '://0' : 'javascript:void(0)';
				document.write('<script id="ie_ready" defer src="' + src + '"><\/script>');
				$('ie_ready').onreadystatechange = function(){
					if (this.readyState == 'complete') domReady();
				};
			}
		} else {
			window.addListener("load", domReady);
			document.addListener("DOMContentLoaded", domReady);
		}
	}

};

window.onDomReady = function(fn){ 
	return this.addEvent('domready', fn); 
};

window.extend({

	getWidth: function(){
		if (this.webkit419) return this.innerWidth;
		if (this.opera) return document.body.clientWidth;
		return document.documentElement.clientWidth;
	},

	getHeight: function(){
		if (this.webkit419) return this.innerHeight;
		if (this.opera) return document.body.clientHeight;
		return document.documentElement.clientHeight;
	},

	getScrollWidth: function(){
		if (this.ie) return Math.max(document.documentElement.offsetWidth, document.documentElement.scrollWidth);
		if (this.webkit) return document.body.scrollWidth;
		return document.documentElement.scrollWidth;
	},

	getScrollHeight: function(){
		if (this.ie) return Math.max(document.documentElement.offsetHeight, document.documentElement.scrollHeight);
		if (this.webkit) return document.body.scrollHeight;
		return document.documentElement.scrollHeight;
	},

	getScrollLeft: function(){
		return this.pageXOffset || document.documentElement.scrollLeft;
	},

	getScrollTop: function(){
		return this.pageYOffset || document.documentElement.scrollTop;
	},

	getSize: function(){
		return {
			'size': {'x': this.getWidth(), 'y': this.getHeight()},
			'scrollSize': {'x': this.getScrollWidth(), 'y': this.getScrollHeight()},
			'scroll': {'x': this.getScrollLeft(), 'y': this.getScrollTop()}
		};
	},
	getPosition: function(){return {'x': 0, 'y': 0};}

});

var Fx = {};

Fx.Base = new Class({

	options: {
		onStart: Class.empty,
		onComplete: Class.empty,
		onCancel: Class.empty,
		transition: function(p){
			return -(Math.cos(Math.PI * p) - 1) / 2;
		},
		duration: 500,
		unit: 'px',
		wait: true,
		fps: 50
	},

	initialize: function(options){
		this.element = this.element || null;
		this.setOptions(options);
		if (this.options.initialize) this.options.initialize.call(this);
	},

	step: function(){
		var time = $time();
		if (time < this.time + this.options.duration){
			this.delta = this.options.transition((time - this.time) / this.options.duration);
			this.setNow();
			this.increase();
		} else {
			this.stop(true);
			this.set(this.to);
			this.fireEvent('onComplete', this.element, 10);
			this.callChain();
		}
	},

	set: function(to){
		this.now = to;
		this.increase();
		return this;
	},

	setNow: function(){
		this.now = this.compute(this.from, this.to);
	},

	compute: function(from, to){
		return (to - from) * this.delta + from;
	},

	start: function(from, to){
		if (!this.options.wait) this.stop();
		else if (this.timer) return this;
		this.from = from;
		this.to = to;
		this.change = this.to - this.from;
		this.time = $time();
		this.timer = this.step.periodical(Math.round(1000 / this.options.fps), this);
		this.fireEvent('onStart', this.element);
		return this;
	},

	stop: function(end){
		if (!this.timer) return this;
		this.timer = $clear(this.timer);
		if (!end) this.fireEvent('onCancel', this.element);
		return this;
	}/*compatibility*/,

	custom: function(from, to){
		return this.start(from, to);
	},

	clearTimer: function(end){
		return this.stop(end);
	}

});

Fx.Base.implement(new Chain, new Events, new Options);

Fx.CSS = {

	select: function(property, to){
		if (property.test(/color/i)) return this.Color;
		var type = $type(to);
		if ((type == 'array') || (type == 'string' && to.contains(' '))) return this.Multi;
		return this.Single;
	},

	parse: function(el, property, fromTo){
		if (!fromTo.push) fromTo = [fromTo];
		var from = fromTo[0], to = fromTo[1];
		if (!$chk(to)){
			to = from;
			from = el.getStyle(property);
		}
		var css = this.select(property, to);
		return {'from': css.parse(from), 'to': css.parse(to), 'css': css};
	}

};

Fx.CSS.Single = {

	parse: function(value){
		return parseFloat(value);
	},

	getNow: function(from, to, fx){
		return fx.compute(from, to);
	},

	getValue: function(value, unit, property){
		if (unit == 'px' && property != 'opacity') value = Math.round(value);
		return value + unit;
	}

};

Fx.CSS.Multi = {

	parse: function(value){
		return value.push ? value : value.split(' ').map(function(v){
			return parseFloat(v);
		});
	},

	getNow: function(from, to, fx){
		var now = [];
		for (var i = 0; i < from.length; i++) now[i] = fx.compute(from[i], to[i]);
		return now;
	},

	getValue: function(value, unit, property){
		if (unit == 'px' && property != 'opacity') value = value.map(Math.round);
		return value.join(unit + ' ') + unit;
	}

};

Fx.CSS.Color = {

	parse: function(value){
		return value.push ? value : value.hexToRgb(true);
	},

	getNow: function(from, to, fx){
		var now = [];
		for (var i = 0; i < from.length; i++) now[i] = Math.round(fx.compute(from[i], to[i]));
		return now;
	},

	getValue: function(value){
		return 'rgb(' + value.join(',') + ')';
	}

};

Fx.Style = Fx.Base.extend({

	initialize: function(el, property, options){
		this.element = $(el);
		this.property = property;
		this.parent(options);
	},

	hide: function(){
		return this.set(0);
	},

	setNow: function(){
		this.now = this.css.getNow(this.from, this.to, this);
	},

	set: function(to){
		this.css = Fx.CSS.select(this.property, to);
		return this.parent(this.css.parse(to));
	},

	start: function(from, to){
		if (this.timer && this.options.wait) return this;
		var parsed = Fx.CSS.parse(this.element, this.property, [from, to]);
		this.css = parsed.css;
		return this.parent(parsed.from, parsed.to);
	},

	increase: function(){
		this.element.setStyle(this.property, this.css.getValue(this.now, this.options.unit, this.property));
	}

});

Element.extend({

	effect: function(property, options){
		return new Fx.Style(this, property, options);
	}

});

Fx.Styles = Fx.Base.extend({

	initialize: function(el, options){
		this.element = $(el);
		this.parent(options);
	},

	setNow: function(){
		for (var p in this.from) this.now[p] = this.css[p].getNow(this.from[p], this.to[p], this);
	},

	set: function(to){
		var parsed = {};
		this.css = {};
		for (var p in to){
			this.css[p] = Fx.CSS.select(p, to[p]);
			parsed[p] = this.css[p].parse(to[p]);
		}
		return this.parent(parsed);
	},

	start: function(obj){
		if (this.timer && this.options.wait) return this;
		this.now = {};
		this.css = {};
		var from = {}, to = {};
		for (var p in obj){
			var parsed = Fx.CSS.parse(this.element, p, obj[p]);
			from[p] = parsed.from;
			to[p] = parsed.to;
			this.css[p] = parsed.css;
		}
		return this.parent(from, to);
	},

	increase: function(){
		for (var p in this.now) this.element.setStyle(p, this.css[p].getValue(this.now[p], this.options.unit, p));
	}

});

Element.extend({

	effects: function(options){
		return new Fx.Styles(this, options);
	}

});

Fx.Elements = Fx.Base.extend({

	initialize: function(elements, options){
		this.elements = $$(elements);
		this.parent(options);
	},

	setNow: function(){
		for (var i in this.from){
			var iFrom = this.from[i], iTo = this.to[i], iCss = this.css[i], iNow = this.now[i] = {};
			for (var p in iFrom) iNow[p] = iCss[p].getNow(iFrom[p], iTo[p], this);
		}
	},

	set: function(to){
		var parsed = {};
		this.css = {};
		for (var i in to){
			var iTo = to[i], iCss = this.css[i] = {}, iParsed = parsed[i] = {};
			for (var p in iTo){
				iCss[p] = Fx.CSS.select(p, iTo[p]);
				iParsed[p] = iCss[p].parse(iTo[p]);
			}
		}
		return this.parent(parsed);
	},

	start: function(obj){
		if (this.timer && this.options.wait) return this;
		this.now = {};
		this.css = {};
		var from = {}, to = {};
		for (var i in obj){
			var iProps = obj[i], iFrom = from[i] = {}, iTo = to[i] = {}, iCss = this.css[i] = {};
			for (var p in iProps){
				var parsed = Fx.CSS.parse(this.elements[i], p, iProps[p]);
				iFrom[p] = parsed.from;
				iTo[p] = parsed.to;
				iCss[p] = parsed.css;
			}
		}
		return this.parent(from, to);
	},

	increase: function(){
		for (var i in this.now){
			var iNow = this.now[i], iCss = this.css[i];
			for (var p in iNow) this.elements[i].setStyle(p, iCss[p].getValue(iNow[p], this.options.unit, p));
		}
	}

});

Fx.Scroll = Fx.Base.extend({

	options: {
		overflown: [],
		offset: {'x': 0, 'y': 0},
		wheelStops: true
	},

	initialize: function(element, options){
		this.now = [];
		this.element = $(element);
		this.bound = {'stop': this.stop.bind(this, false)};
		this.parent(options);
		if (this.options.wheelStops){
			this.addEvent('onStart', function(){
				document.addEvent('mousewheel', this.bound.stop);
			}.bind(this));
			this.addEvent('onComplete', function(){
				document.removeEvent('mousewheel', this.bound.stop);
			}.bind(this));
		}
	},

	setNow: function(){
		for (var i = 0; i < 2; i++) this.now[i] = this.compute(this.from[i], this.to[i]);
	},

	scrollTo: function(x, y){
		if (this.timer && this.options.wait) return this;
		var el = this.element.getSize();
		var values = {'x': x, 'y': y};
		for (var z in el.size){
			var max = el.scrollSize[z] - el.size[z];
			if ($chk(values[z])) values[z] = ($type(values[z]) == 'number') ? values[z].limit(0, max) : max;
			else values[z] = el.scroll[z];
			values[z] += this.options.offset[z];
		}
		return this.start([el.scroll.x, el.scroll.y], [values.x, values.y]);
	},

	toTop: function(){
		return this.scrollTo(false, 0);
	},

	toBottom: function(){
		return this.scrollTo(false, 'full');
	},

	toLeft: function(){
		return this.scrollTo(0, false);
	},

	toRight: function(){
		return this.scrollTo('full', false);
	},

	toElement: function(el){
		var parent = this.element.getPosition(this.options.overflown);
		var target = $(el).getPosition(this.options.overflown);
		return this.scrollTo(target.x - parent.x, target.y - parent.y);
	},

	increase: function(){
		this.element.scrollTo(this.now[0], this.now[1]);
	}

});

Fx.Slide = Fx.Base.extend({

	options: {
		mode: 'vertical'
	},

	initialize: function(el, options){
		this.element = $(el);
		this.wrapper = new Element('div', {'styles': $extend(this.element.getStyles('margin'), {'overflow': 'hidden'})}).injectAfter(this.element).adopt(this.element);
		this.element.setStyle('margin', 0);
		this.setOptions(options);
		this.now = [];
		this.parent(this.options);
		this.open = true;
		this.addEvent('onComplete', function(){
			this.open = (this.now[0] === 0);
		});
		if (window.webkit419) this.addEvent('onComplete', function(){
			if (this.open) this.element.remove().inject(this.wrapper);
		});
	},

	setNow: function(){
		for (var i = 0; i < 2; i++) this.now[i] = this.compute(this.from[i], this.to[i]);
	},

	vertical: function(){
		this.margin = 'margin-top';
		this.layout = 'height';
		this.offset = this.element.offsetHeight;
	},

	horizontal: function(){
		this.margin = 'margin-left';
		this.layout = 'width';
		this.offset = this.element.offsetWidth;
	},

	slideIn: function(mode){
		this[mode || this.options.mode]();
		return this.start([this.element.getStyle(this.margin).toInt(), this.wrapper.getStyle(this.layout).toInt()], [0, this.offset]);
	},

	slideOut: function(mode){
		this[mode || this.options.mode]();
		return this.start([this.element.getStyle(this.margin).toInt(), this.wrapper.getStyle(this.layout).toInt()], [-this.offset, 0]);
	},

	hide: function(mode){
		this[mode || this.options.mode]();
		this.open = false;
		return this.set([-this.offset, 0]);
	},

	show: function(mode){
		this[mode || this.options.mode]();
		this.open = true;
		return this.set([0, this.offset]);
	},

	toggle: function(mode){
		if (this.wrapper.offsetHeight == 0 || this.wrapper.offsetWidth == 0) return this.slideIn(mode);
		return this.slideOut(mode);
	},

	increase: function(){
		this.element.setStyle(this.margin, this.now[0] + this.options.unit);
		this.wrapper.setStyle(this.layout, this.now[1] + this.options.unit);
	}

});

Fx.Transition = function(transition, params){
	params = params || [];
	if ($type(params) != 'array') params = [params];
	return $extend(transition, {
		easeIn: function(pos){
			return transition(pos, params);
		},
		easeOut: function(pos){
			return 1 - transition(1 - pos, params);
		},
		easeInOut: function(pos){
			return (pos <= 0.5) ? transition(2 * pos, params) / 2 : (2 - transition(2 * (1 - pos), params)) / 2;
		}
	});
};

Fx.Transitions = new Abstract({

	linear: function(p){
		return p;
	}

});

Fx.Transitions.extend = function(transitions){
	for (var transition in transitions){
		Fx.Transitions[transition] = new Fx.Transition(transitions[transition]);
		Fx.Transitions.compat(transition);
	}
};

Fx.Transitions.compat = function(transition){
	['In', 'Out', 'InOut'].each(function(easeType){
		Fx.Transitions[transition.toLowerCase() + easeType] = Fx.Transitions[transition]['ease' + easeType];
	});
};

Fx.Transitions.extend({

	Pow: function(p, x){
		return Math.pow(p, x[0] || 6);
	},

	Expo: function(p){
		return Math.pow(2, 8 * (p - 1));
	},

	Circ: function(p){
		return 1 - Math.sin(Math.acos(p));
	},

	Sine: function(p){
		return 1 - Math.sin((1 - p) * Math.PI / 2);
	},

	Back: function(p, x){
		x = x[0] || 1.618;
		return Math.pow(p, 2) * ((x + 1) * p - x);
	},

	Bounce: function(p){
		var value;
		for (var a = 0, b = 1; 1; a += b, b /= 2){
			if (p >= (7 - 4 * a) / 11){
				value = - Math.pow((11 - 6 * a - 11 * p) / 4, 2) + b * b;
				break;
			}
		}
		return value;
	},

	Elastic: function(p, x){
		return Math.pow(2, 10 * --p) * Math.cos(20 * p * Math.PI * (x[0] || 1) / 3);
	}

});

['Quad', 'Cubic', 'Quart', 'Quint'].each(function(transition, i){
	Fx.Transitions[transition] = new Fx.Transition(function(p){
		return Math.pow(p, [i + 2]);
	});
	Fx.Transitions.compat(transition);
});

var Drag = {};

Drag.Base = new Class({

	options: {
		handle: false,
		unit: 'px',
		onStart: Class.empty,
		onBeforeStart: Class.empty,
		onComplete: Class.empty,
		onSnap: Class.empty,
		onDrag: Class.empty,
		limit: false,
		modifiers: {x: 'left', y: 'top'},
		grid: false,
		snap: 6
	},

	initialize: function(el, options){
		this.setOptions(options);
		this.element = $(el);
		this.handle = $(this.options.handle) || this.element;
		this.mouse = {'now': {}, 'pos': {}};
		this.value = {'start': {}, 'now': {}};
		this.bound = {
			'start': this.start.bindWithEvent(this),
			'check': this.check.bindWithEvent(this),
			'drag': this.drag.bindWithEvent(this),
			'stop': this.stop.bind(this)
		};
		this.attach();
		if (this.options.initialize) this.options.initialize.call(this);
	},

	attach: function(){
		this.handle.addEvent('mousedown', this.bound.start);
		return this;
	},

	detach: function(){
		this.handle.removeEvent('mousedown', this.bound.start);
		return this;
	},

	start: function(event){
		this.fireEvent('onBeforeStart', this.element);
		this.mouse.start = event.page;
		var limit = this.options.limit;
		this.limit = {'x': [], 'y': []};
		for (var z in this.options.modifiers){
			if (!this.options.modifiers[z]) continue;
			this.value.now[z] = this.element.getStyle(this.options.modifiers[z]).toInt();
			this.mouse.pos[z] = event.page[z] - this.value.now[z];
			if (limit && limit[z]){
				for (var i = 0; i < 2; i++){
					if ($chk(limit[z][i])) this.limit[z][i] = ($type(limit[z][i]) == 'function') ? limit[z][i]() : limit[z][i];
				}
			}
		}
		if ($type(this.options.grid) == 'number') this.options.grid = {'x': this.options.grid, 'y': this.options.grid};
		document.addListener('mousemove', this.bound.check);
		document.addListener('mouseup', this.bound.stop);
		this.fireEvent('onStart', this.element);
		event.stop();
	},

	check: function(event){
		var distance = Math.round(Math.sqrt(Math.pow(event.page.x - this.mouse.start.x, 2) + Math.pow(event.page.y - this.mouse.start.y, 2)));
		if (distance > this.options.snap){
			document.removeListener('mousemove', this.bound.check);
			document.addListener('mousemove', this.bound.drag);
			this.drag(event);
			this.fireEvent('onSnap', this.element);
		}
		event.stop();
	},

	drag: function(event){
		this.out = false;
		this.mouse.now = event.page;
		for (var z in this.options.modifiers){
			if (!this.options.modifiers[z]) continue;
			this.value.now[z] = this.mouse.now[z] - this.mouse.pos[z];
			if (this.limit[z]){
				if ($chk(this.limit[z][1]) && (this.value.now[z] > this.limit[z][1])){
					this.value.now[z] = this.limit[z][1];
					this.out = true;
				} else if ($chk(this.limit[z][0]) && (this.value.now[z] < this.limit[z][0])){
					this.value.now[z] = this.limit[z][0];
					this.out = true;
				}
			}
			if (this.options.grid[z]) this.value.now[z] -= (this.value.now[z] % this.options.grid[z]);
			this.element.setStyle(this.options.modifiers[z], this.value.now[z] + this.options.unit);
		}
		this.fireEvent('onDrag', this.element);
		event.stop();
	},

	stop: function(){
		document.removeListener('mousemove', this.bound.check);
		document.removeListener('mousemove', this.bound.drag);
		document.removeListener('mouseup', this.bound.stop);
		this.fireEvent('onComplete', this.element);
	}

});

Drag.Base.implement(new Events, new Options);

Element.extend({

	makeResizable: function(options){
		return new Drag.Base(this, $merge({modifiers: {x: 'width', y: 'height'}}, options));
	}

});

Drag.Move = Drag.Base.extend({

	options: {
		droppables: [],
		container: false,
		overflown: []
	},

	initialize: function(el, options){
		this.setOptions(options);
		this.element = $(el);
		this.droppables = $$(this.options.droppables);
		this.container = $(this.options.container);
		this.position = {'element': this.element.getStyle('position'), 'container': false};
		if (this.container) this.position.container = this.container.getStyle('position');
		if (!['relative', 'absolute', 'fixed'].contains(this.position.element)) this.position.element = 'absolute';
		var top = this.element.getStyle('top').toInt();
		var left = this.element.getStyle('left').toInt();
		if (this.position.element == 'absolute' && !['relative', 'absolute', 'fixed'].contains(this.position.container)){
			top = $chk(top) ? top : this.element.getTop(this.options.overflown);
			left = $chk(left) ? left : this.element.getLeft(this.options.overflown);
		} else {
			top = $chk(top) ? top : 0;
			left = $chk(left) ? left : 0;
		}
		this.element.setStyles({'top': top, 'left': left, 'position': this.position.element});
		this.parent(this.element);
	},

	start: function(event){
		this.overed = null;
		if (this.container){
			var cont = this.container.getCoordinates();
			var el = this.element.getCoordinates();
			if (this.position.element == 'absolute' && !['relative', 'absolute', 'fixed'].contains(this.position.container)){
				this.options.limit = {
					'x': [cont.left, cont.right - el.width],
					'y': [cont.top, cont.bottom - el.height]
				};
			} else {
				this.options.limit = {
					'y': [0, cont.height - el.height],
					'x': [0, cont.width - el.width]
				};
			}
		}
		this.parent(event);
	},

	drag: function(event){
		this.parent(event);
		var overed = this.out ? false : this.droppables.filter(this.checkAgainst, this).getLast();
		if (this.overed != overed){
			if (this.overed) this.overed.fireEvent('leave', [this.element, this]);
			this.overed = overed ? overed.fireEvent('over', [this.element, this]) : null;
		}
		return this;
	},

	checkAgainst: function(el){
		el = el.getCoordinates(this.options.overflown);
		var now = this.mouse.now;
		return (now.x > el.left && now.x < el.right && now.y < el.bottom && now.y > el.top);
	},

	stop: function(){
		if (this.overed && !this.out) this.overed.fireEvent('drop', [this.element, this]);
		else this.element.fireEvent('emptydrop', this);
		this.parent();
		return this;
	}

});

Element.extend({

	makeDraggable: function(options){
		return new Drag.Move(this, options);
	}

});

var XHR = new Class({

	options: {
		method: 'post',
		async: true,
		onRequest: Class.empty,
		onSuccess: Class.empty,
		onFailure: Class.empty,
		urlEncoded: true,
		encoding: 'utf-8',
		autoCancel: false,
		headers: {}
	},

	setTransport: function(){
		this.transport = (window.XMLHttpRequest) ? new XMLHttpRequest() : (window.ie ? new ActiveXObject('Microsoft.XMLHTTP') : false);
		return this;
	},

	initialize: function(options){
		this.setTransport().setOptions(options);
		this.options.isSuccess = this.options.isSuccess || this.isSuccess;
		this.headers = {};
		if (this.options.urlEncoded && this.options.method == 'post'){
			var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : '';
			this.setHeader('Content-type', 'application/x-www-form-urlencoded' + encoding);
		}
		if (this.options.initialize) this.options.initialize.call(this);
	},

	onStateChange: function(){
		if (this.transport.readyState != 4 || !this.running) return;
		this.running = false;
		var status = 0;
		try {status = this.transport.status;} catch(e){};
		if (this.options.isSuccess.call(this, status)) this.onSuccess();
		else this.onFailure();
		this.transport.onreadystatechange = Class.empty;
	},

	isSuccess: function(status){
		return ((status >= 200) && (status < 300));
	},

	onSuccess: function(){
		this.response = {
			'text': this.transport.responseText,
			'xml': this.transport.responseXML
		};
		this.fireEvent('onSuccess', [this.response.text, this.response.xml]);
		this.callChain();
	},

	onFailure: function(){
		this.fireEvent('onFailure', this.transport);
	},

	setHeader: function(name, value){
		this.headers[name] = value;
		return this;
	},

	send: function(url, data){
		if (this.options.autoCancel) this.cancel();
		else if (this.running) return this;
		this.running = true;
		if (data && this.options.method == 'get'){
			url = url + (url.contains('?') ? '&' : '?') + data;
			data = null;
		}
		this.transport.open(this.options.method.toUpperCase(), url, this.options.async);
		this.transport.onreadystatechange = this.onStateChange.bind(this);
		if ((this.options.method == 'post') && this.transport.overrideMimeType) this.setHeader('Connection', 'close');
		$extend(this.headers, this.options.headers);
		for (var type in this.headers) try {this.transport.setRequestHeader(type, this.headers[type]);} catch(e){};
		this.fireEvent('onRequest');
		this.transport.send($pick(data, null));
		return this;
	},

	cancel: function(){
		if (!this.running) return this;
		this.running = false;
		this.transport.abort();
		this.transport.onreadystatechange = Class.empty;
		this.setTransport();
		this.fireEvent('onCancel');
		return this;
	}

});

XHR.implement(new Chain, new Events, new Options);

var Ajax = XHR.extend({

	options: {
		data: null,
		update: null,
		onComplete: Class.empty,
		evalScripts: false,
		evalResponse: false
	},

	initialize: function(url, options){
		this.addEvent('onSuccess', this.onComplete);
		this.setOptions(options);
		this.options.data = this.options.data || this.options.postBody;
		if (!['post', 'get'].contains(this.options.method)){
			this._method = '_method=' + this.options.method;
			this.options.method = 'post';
		}
		this.parent();
		this.setHeader('X-Requested-With', 'XMLHttpRequest');
		this.setHeader('Accept', 'text/javascript, text/html, application/xml, text/xml, */*');
		this.url = url;
	},

	onComplete: function(){
		if (this.options.update) $(this.options.update).empty().setHTML(this.response.text);
		if (this.options.evalScripts || this.options.evalResponse) this.evalScripts();
		this.fireEvent('onComplete', [this.response.text, this.response.xml], 20);
	},

	request: function(data){
		data = data || this.options.data;
		switch($type(data)){
			case 'element': data = $(data).toQueryString(); break;
			case 'object': data = Object.toQueryString(data);
		}
		if (this._method) data = (data) ? [this._method, data].join('&') : this._method;
		return this.send(this.url, data);
	},

	evalScripts: function(){
		var script, scripts;
		if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) scripts = this.response.text;
		else {
			scripts = [];
			var regexp = /<script[^>]*>([\s\S]*?)<\/script>/gi;
			while ((script = regexp.exec(this.response.text))) scripts.push(script[1]);
			scripts = scripts.join('\n');
		}
		if (scripts) (window.execScript) ? window.execScript(scripts) : window.setTimeout(scripts, 0);
	},

	getHeader: function(name){
		try {return this.transport.getResponseHeader(name);} catch(e){};
		return null;
	}

});

Object.toQueryString = function(source){
	var queryString = [];
	for (var property in source) queryString.push(encodeURIComponent(property) + '=' + encodeURIComponent(source[property]));
	return queryString.join('&');
};

Element.extend({

	send: function(options){
		return new Ajax(this.getProperty('action'), $merge({data: this.toQueryString()}, options, {method: 'post'})).request();
	}

});

var Cookie = new Abstract({

	options: {
		domain: false,
		path: false,
		duration: false,
		secure: false
	},

	set: function(key, value, options){
		options = $merge(this.options, options);
		value = encodeURIComponent(value);
		if (options.domain) value += '; domain=' + options.domain;
		if (options.path) value += '; path=' + options.path;
		if (options.duration){
			var date = new Date();
			date.setTime(date.getTime() + options.duration * 24 * 60 * 60 * 1000);
			value += '; expires=' + date.toGMTString();
		}
		if (options.secure) value += '; secure';
		document.cookie = key + '=' + value;
		return $extend(options, {'key': key, 'value': value});
	},

	get: function(key){
		var value = document.cookie.match('(?:^|;)\\s*' + key.escapeRegExp() + '=([^;]*)');
		return value ? decodeURIComponent(value[1]) : false;
	},

	remove: function(cookie, options){
		if ($type(cookie) == 'object') this.set(cookie.key, '', $merge(cookie, {duration: -1}));
		else this.set(cookie, '', $merge(options, {duration: -1}));
	}

});

var Json = {

	toString: function(obj){
		switch($type(obj)){
			case 'string':
				return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';
			case 'array':
				return '[' + obj.map(Json.toString).join(',') + ']';
			case 'object':
				var string = [];
				for (var property in obj) string.push(Json.toString(property) + ':' + Json.toString(obj[property]));
				return '{' + string.join(',') + '}';
			case 'number':
				if (isFinite(obj)) break;
			case false:
				return 'null';
		}
		return String(obj);
	},

	evaluate: function(str, secure){
		return (($type(str) != 'string') || (secure && !str.test(/^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/))) ? null : eval('(' + str + ')');
	}

};

Json.Remote = XHR.extend({

	initialize: function(url, options){
		this.url = url;
		this.addEvent('onSuccess', this.onComplete);
		this.parent(options);
		this.setHeader('X-Request', 'JSON');
	},

	send: function(obj){
		return this.parent(this.url, 'json=' + Json.toString(obj));
	},

	onComplete: function(){
		this.fireEvent('onComplete', [Json.evaluate(this.response.text, this.options.secure)]);
	}

});

var Asset = new Abstract({

	javascript: function(source, properties){
		properties = $merge({
			'onload': Class.empty
		}, properties);
		var script = new Element('script', {'src': source}).addEvents({
			'load': properties.onload,
			'readystatechange': function(){
				if (this.readyState == 'complete') this.fireEvent('load');
			}
		});
		delete properties.onload;
		return script.setProperties(properties).inject(document.head);
	},

	css: function(source, properties){
		return new Element('link', $merge({
			'rel': 'stylesheet', 'media': 'screen', 'type': 'text/css', 'href': source
		}, properties)).inject(document.head);
	},

	image: function(source, properties){
		properties = $merge({
			'onload': Class.empty,
			'onabort': Class.empty,
			'onerror': Class.empty
		}, properties);
		var image = new Image();
		image.src = source;
		var element = new Element('img', {'src': source});
		['load', 'abort', 'error'].each(function(type){
			var event = properties['on' + type];
			delete properties['on' + type];
			element.addEvent(type, function(){
				this.removeEvent(type, arguments.callee);
				event.call(this);
			});
		});
		if (image.width && image.height) element.fireEvent('load', element, 1);
		return element.setProperties(properties);
	},

	images: function(sources, options){
		options = $merge({
			onComplete: Class.empty,
			onProgress: Class.empty
		}, options);
		if (!sources.push) sources = [sources];
		var images = [];
		var counter = 0;
		sources.each(function(source){
			var img = new Asset.image(source, {
				'onload': function(){
					options.onProgress.call(this, counter);
					counter++;
					if (counter == sources.length) options.onComplete();
				}
			});
			images.push(img);
		});
		return new Elements(images);
	}

});

var Hash = new Class({

	length: 0,

	initialize: function(object){
		this.obj = object || {};
		this.setLength();
	},

	get: function(key){
		return (this.hasKey(key)) ? this.obj[key] : null;
	},

	hasKey: function(key){
		return (key in this.obj);
	},

	set: function(key, value){
		if (!this.hasKey(key)) this.length++;
		this.obj[key] = value;
		return this;
	},

	setLength: function(){
		this.length = 0;
		for (var p in this.obj) this.length++;
		return this;
	},

	remove: function(key){
		if (this.hasKey(key)){
			delete this.obj[key];
			this.length--;
		}
		return this;
	},

	each: function(fn, bind){
		$each(this.obj, fn, bind);
	},

	extend: function(obj){
		$extend(this.obj, obj);
		return this.setLength();
	},

	merge: function(){
		this.obj = $merge.apply(null, [this.obj].extend(arguments));
		return this.setLength();
	},

	empty: function(){
		this.obj = {};
		this.length = 0;
		return this;
	},

	keys: function(){
		var keys = [];
		for (var property in this.obj) keys.push(property);
		return keys;
	},

	values: function(){
		var values = [];
		for (var property in this.obj) values.push(this.obj[property]);
		return values;
	}

});

function $H(obj){
	return new Hash(obj);
};

Hash.Cookie = Hash.extend({

	initialize: function(name, options){
		this.name = name;
		this.options = $extend({'autoSave': true}, options || {});
		this.load();
	},

	save: function(){
		if (this.length == 0){
			Cookie.remove(this.name, this.options);
			return true;
		}
		var str = Json.toString(this.obj);
		if (str.length > 4096) return false;
		Cookie.set(this.name, str, this.options);
		return true;
	},

	load: function(){
		this.obj = Json.evaluate(Cookie.get(this.name), true) || {};
		this.setLength();
	}

});

Hash.Cookie.Methods = {};
['extend', 'set', 'merge', 'empty', 'remove'].each(function(method){
	Hash.Cookie.Methods[method] = function(){
		Hash.prototype[method].apply(this, arguments);
		if (this.options.autoSave) this.save();
		return this;
	};
});
Hash.Cookie.implement(Hash.Cookie.Methods);

var Color = new Class({

	initialize: function(color, type){
		type = type || (color.push ? 'rgb' : 'hex');
		var rgb, hsb;
		switch(type){
			case 'rgb':
				rgb = color;
				hsb = rgb.rgbToHsb();
				break;
			case 'hsb':
				rgb = color.hsbToRgb();
				hsb = color;
				break;
			default:
				rgb = color.hexToRgb(true);
				hsb = rgb.rgbToHsb();
		}
		rgb.hsb = hsb;
		rgb.hex = rgb.rgbToHex();
		return $extend(rgb, Color.prototype);
	},

	mix: function(){
		var colors = $A(arguments);
		var alpha = ($type(colors[colors.length - 1]) == 'number') ? colors.pop() : 50;
		var rgb = this.copy();
		colors.each(function(color){
			color = new Color(color);
			for (var i = 0; i < 3; i++) rgb[i] = Math.round((rgb[i] / 100 * (100 - alpha)) + (color[i] / 100 * alpha));
		});
		return new Color(rgb, 'rgb');
	},

	invert: function(){
		return new Color(this.map(function(value){
			return 255 - value;
		}));
	},

	setHue: function(value){
		return new Color([value, this.hsb[1], this.hsb[2]], 'hsb');
	},

	setSaturation: function(percent){
		return new Color([this.hsb[0], percent, this.hsb[2]], 'hsb');
	},

	setBrightness: function(percent){
		return new Color([this.hsb[0], this.hsb[1], percent], 'hsb');
	}

});

function $RGB(r, g, b){
	return new Color([r, g, b], 'rgb');
};

function $HSB(h, s, b){
	return new Color([h, s, b], 'hsb');
};

Array.extend({

	rgbToHsb: function(){
		var red = this[0], green = this[1], blue = this[2];
		var hue, saturation, brightness;
		var max = Math.max(red, green, blue), min = Math.min(red, green, blue);
		var delta = max - min;
		brightness = max / 255;
		saturation = (max != 0) ? delta / max : 0;
		if (saturation == 0){
			hue = 0;
		} else {
			var rr = (max - red) / delta;
			var gr = (max - green) / delta;
			var br = (max - blue) / delta;
			if (red == max) hue = br - gr;
			else if (green == max) hue = 2 + rr - br;
			else hue = 4 + gr - rr;
			hue /= 6;
			if (hue < 0) hue++;
		}
		return [Math.round(hue * 360), Math.round(saturation * 100), Math.round(brightness * 100)];
	},

	hsbToRgb: function(){
		var br = Math.round(this[2] / 100 * 255);
		if (this[1] == 0){
			return [br, br, br];
		} else {
			var hue = this[0] % 360;
			var f = hue % 60;
			var p = Math.round((this[2] * (100 - this[1])) / 10000 * 255);
			var q = Math.round((this[2] * (6000 - this[1] * f)) / 600000 * 255);
			var t = Math.round((this[2] * (6000 - this[1] * (60 - f))) / 600000 * 255);
			switch(Math.floor(hue / 60)){
				case 0: return [br, t, p];
				case 1: return [q, br, p];
				case 2: return [p, br, t];
				case 3: return [p, q, br];
				case 4: return [t, p, br];
				case 5: return [br, p, q];
			}
		}
		return false;
	}

});

var Scroller = new Class({

	options: {
		area: 20,
		velocity: 1,
		onChange: function(x, y){
			this.element.scrollTo(x, y);
		}
	},

	initialize: function(element, options){
		this.setOptions(options);
		this.element = $(element);
		this.mousemover = ([window, document].contains(element)) ? $(document.body) : this.element;
	},

	start: function(){
		this.coord = this.getCoords.bindWithEvent(this);
		this.mousemover.addListener('mousemove', this.coord);
	},

	stop: function(){
		this.mousemover.removeListener('mousemove', this.coord);
		this.timer = $clear(this.timer);
	},

	getCoords: function(event){
		this.page = (this.element == window) ? event.client : event.page;
		if (!this.timer) this.timer = this.scroll.periodical(50, this);
	},

	scroll: function(){
		var el = this.element.getSize();
		var pos = this.element.getPosition();

		var change = {'x': 0, 'y': 0};
		for (var z in this.page){
			if (this.page[z] < (this.options.area + pos[z]) && el.scroll[z] != 0)
				change[z] = (this.page[z] - this.options.area - pos[z]) * this.options.velocity;
			else if (this.page[z] + this.options.area > (el.size[z] + pos[z]) && el.scroll[z] + el.size[z] != el.scrollSize[z])
				change[z] = (this.page[z] - el.size[z] + this.options.area - pos[z]) * this.options.velocity;
		}
		if (change.y || change.x) this.fireEvent('onChange', [el.scroll.x + change.x, el.scroll.y + change.y]);
	}

});

Scroller.implement(new Events, new Options);

var Slider = new Class({

	options: {
		onChange: Class.empty,
		onComplete: Class.empty,
		onTick: function(pos){
			this.knob.setStyle(this.p, pos);
		},
		mode: 'horizontal',
		steps: 100,
		offset: 0
	},

	initialize: function(el, knob, options){
		this.element = $(el);
		this.knob = $(knob);
		this.setOptions(options);
		this.previousChange = -1;
		this.previousEnd = -1;
		this.step = -1;
		this.element.addEvent('mousedown', this.clickedElement.bindWithEvent(this));
		var mod, offset;
		switch(this.options.mode){
			case 'horizontal':
				this.z = 'x';
				this.p = 'left';
				mod = {'x': 'left', 'y': false};
				offset = 'offsetWidth';
				break;
			case 'vertical':
				this.z = 'y';
				this.p = 'top';
				mod = {'x': false, 'y': 'top'};
				offset = 'offsetHeight';
		}
		this.max = this.element[offset] - this.knob[offset] + (this.options.offset * 2);
		this.half = this.knob[offset]/2;
		this.getPos = this.element['get' + this.p.capitalize()].bind(this.element);
		this.knob.setStyle('position', 'relative').setStyle(this.p, - this.options.offset);
		var lim = {};
		lim[this.z] = [- this.options.offset, this.max - this.options.offset];
		this.drag = new Drag.Base(this.knob, {
			limit: lim,
			modifiers: mod,
			snap: 0,
			onStart: function(){
				this.draggedKnob();
			}.bind(this),
			onDrag: function(){
				this.draggedKnob();
			}.bind(this),
			onComplete: function(){
				this.draggedKnob();
				this.end();
			}.bind(this)
		});
		if (this.options.initialize) this.options.initialize.call(this);
	},

	set: function(step){
		this.step = step.limit(0, this.options.steps);
		this.checkStep();
		this.end();
		this.fireEvent('onTick', this.toPosition(this.step));
		return this;
	},

	clickedElement: function(event){
		var position = event.page[this.z] - this.getPos() - this.half;
		position = position.limit(-this.options.offset, this.max -this.options.offset);
		this.step = this.toStep(position);
		this.checkStep();
		this.end();
		this.fireEvent('onTick', position);
	},

	draggedKnob: function(){
		this.step = this.toStep(this.drag.value.now[this.z]);
		this.checkStep();
	},

	checkStep: function(){
		if (this.previousChange != this.step){
			this.previousChange = this.step;
			this.fireEvent('onChange', this.step);
		}
	},

	end: function(){
		if (this.previousEnd !== this.step){
			this.previousEnd = this.step;
			this.fireEvent('onComplete', this.step + '');
		}
	},

	toStep: function(position){
		return Math.round((position + this.options.offset) / this.max * this.options.steps);
	},

	toPosition: function(step){
		return this.max * step / this.options.steps;
	}

});

Slider.implement(new Events);
Slider.implement(new Options);

var SmoothScroll = Fx.Scroll.extend({

	initialize: function(options){
		this.parent(window, options);
		this.links = (this.options.links) ? $$(this.options.links) : $$(document.links);
		var location = window.location.href.match(/^[^#]*/)[0] + '#';
		this.links.each(function(link){
			if (link.href.indexOf(location) != 0) return;
			var anchor = link.href.substr(location.length);
			if (anchor && $(anchor)) this.useLink(link, anchor);
		}, this);
		if (!window.webkit419) this.addEvent('onComplete', function(){
			window.location.hash = this.anchor;
		});
	},

	useLink: function(link, anchor){
		link.addEvent('click', function(event){
			this.anchor = anchor;
			this.toElement(anchor);
			event.stop();
		}.bindWithEvent(this));
	}

});

var Sortables = new Class({

	options: {
		handles: false,
		onStart: Class.empty,
		onComplete: Class.empty,
		ghost: true,
		snap: 3,
		onDragStart: function(element, ghost){
			ghost.setStyle('opacity', 0.7);
			element.setStyle('opacity', 0.7);
		},
		onDragComplete: function(element, ghost){
			element.setStyle('opacity', 1);
			ghost.remove();
			this.trash.remove();
		}
	},

	initialize: function(list, options){
		this.setOptions(options);
		this.list = $(list);
		this.elements = this.list.getChildren();
		this.handles = (this.options.handles) ? $$(this.options.handles) : this.elements;
		this.bound = {
			'start': [],
			'moveGhost': this.moveGhost.bindWithEvent(this)
		};
		for (var i = 0, l = this.handles.length; i < l; i++){
			this.bound.start[i] = this.start.bindWithEvent(this, this.elements[i]);
		}
		this.attach();
		if (this.options.initialize) this.options.initialize.call(this);
		this.bound.move = this.move.bindWithEvent(this);
		this.bound.end = this.end.bind(this);
	},

	attach: function(){
		this.handles.each(function(handle, i){
			handle.addEvent('mousedown', this.bound.start[i]);
		}, this);
	},

	detach: function(){
		this.handles.each(function(handle, i){
			handle.removeEvent('mousedown', this.bound.start[i]);
		}, this);
	},

	start: function(event, el){
		this.active = el;
		this.coordinates = this.list.getCoordinates();
		if (this.options.ghost){
			var position = el.getPosition();
			this.offset = event.page.y - position.y;
			this.trash = new Element('div').inject(document.body);
			this.ghost = el.clone().inject(this.trash).setStyles({
				'position': 'absolute',
				'left': position.x,
				'top': event.page.y - this.offset
			});
			document.addListener('mousemove', this.bound.moveGhost);
			this.fireEvent('onDragStart', [el, this.ghost]);
		}
		document.addListener('mousemove', this.bound.move);
		document.addListener('mouseup', this.bound.end);
		this.fireEvent('onStart', el);
		event.stop();
	},

	moveGhost: function(event){
		var value = event.page.y - this.offset;
		value = value.limit(this.coordinates.top, this.coordinates.bottom - this.ghost.offsetHeight);
		this.ghost.setStyle('top', value);
		event.stop();
	},

	move: function(event){
		var now = event.page.y;
		this.previous = this.previous || now;
		var up = ((this.previous - now) > 0);
		var prev = this.active.getPrevious();
		var next = this.active.getNext();
		if (prev && up && now < prev.getCoordinates().bottom) this.active.injectBefore(prev);
		if (next && !up && now > next.getCoordinates().top) this.active.injectAfter(next);
		this.previous = now;
	},

	serialize: function(converter){
		return this.list.getChildren().map(converter || function(el){
			return this.elements.indexOf(el);
		}, this);
	},

	end: function(){
		this.previous = null;
		document.removeListener('mousemove', this.bound.move);
		document.removeListener('mouseup', this.bound.end);
		if (this.options.ghost){
			document.removeListener('mousemove', this.bound.moveGhost);
			this.fireEvent('onDragComplete', [this.active, this.ghost]);
		}
		this.fireEvent('onComplete', this.active);
	}

});

Sortables.implement(new Events, new Options);

var Tips = new Class({

	options: {
		onShow: function(tip){
			tip.setStyle('visibility', 'visible');
		},
		onHide: function(tip){
			tip.setStyle('visibility', 'hidden');
		},
		maxTitleChars: 30,
		showDelay: 100,
		hideDelay: 100,
		className: 'tool',
		offsets: {'x': 16, 'y': 16},
		fixed: false
	},

	initialize: function(elements, options){
		this.setOptions(options);
		this.toolTip = new Element('div', {
			'class': this.options.className + '-tip',
			'styles': {
				'position': 'absolute',
				'top': '0',
				'left': '0',
				'visibility': 'hidden'
			}
		}).inject(document.body);
		this.wrapper = new Element('div').inject(this.toolTip);
		$$(elements).each(this.build, this);
		if (this.options.initialize) this.options.initialize.call(this);
	},

	build: function(el){
		el.$tmp.myTitle = (el.href && el.getTag() == 'a') ? el.href.replace('http://', '') : (el.rel || false);
		if (el.title){
			var dual = el.title.split('::');
			if (dual.length > 1){
				el.$tmp.myTitle = dual[0].trim();
				el.$tmp.myText = dual[1].trim();
			} else {
				el.$tmp.myText = el.title;
			}
			el.removeAttribute('title');
		} else {
			el.$tmp.myText = false;
		}
		if (el.$tmp.myTitle && el.$tmp.myTitle.length > this.options.maxTitleChars) el.$tmp.myTitle = el.$tmp.myTitle.substr(0, this.options.maxTitleChars - 1) + "&hellip;";
		el.addEvent('mouseenter', function(event){
			this.start(el);
			if (!this.options.fixed) this.locate(event);
			else this.position(el);
		}.bind(this));
		if (!this.options.fixed) el.addEvent('mousemove', this.locate.bindWithEvent(this));
		var end = this.end.bind(this);
		el.addEvent('mouseleave', end);
		el.addEvent('trash', end);
	},

	start: function(el){
		this.wrapper.empty();
		if (el.$tmp.myTitle){
			this.title = new Element('span').inject(new Element('div', {'class': this.options.className + '-title'}).inject(this.wrapper)).setHTML(el.$tmp.myTitle);
		}
		if (el.$tmp.myText){
			this.text = new Element('span').inject(new Element('div', {'class': this.options.className + '-text'}).inject(this.wrapper)).setHTML(el.$tmp.myText);
		}
		$clear(this.timer);
		this.timer = this.show.delay(this.options.showDelay, this);
	},

	end: function(event){
		$clear(this.timer);
		this.timer = this.hide.delay(this.options.hideDelay, this);
	},

	position: function(element){
		var pos = element.getPosition();
		this.toolTip.setStyles({
			'left': pos.x + this.options.offsets.x,
			'top': pos.y + this.options.offsets.y
		});
	},

	locate: function(event){
		var win = {'x': window.getWidth(), 'y': window.getHeight()};
		var scroll = {'x': window.getScrollLeft(), 'y': window.getScrollTop()};
		var tip = {'x': this.toolTip.offsetWidth, 'y': this.toolTip.offsetHeight};
		var prop = {'x': 'left', 'y': 'top'};
		for (var z in prop){
			var pos = event.page[z] + this.options.offsets[z];
			if ((pos + tip[z] - scroll[z]) > win[z]) pos = event.page[z] - this.options.offsets[z] - tip[z];
			this.toolTip.setStyle(prop[z], pos);
		};
	},

	show: function(){
		if (this.options.timeout) this.timer = this.hide.delay(this.options.timeout, this);
		this.fireEvent('onShow', [this.toolTip]);
	},

	hide: function(){
		this.fireEvent('onHide', [this.toolTip]);
	}

});

Tips.implement(new Events, new Options);

var Group = new Class({

	initialize: function(){
		this.instances = $A(arguments);
		this.events = {};
		this.checker = {};
	},

	addEvent: function(type, fn){
		this.checker[type] = this.checker[type] || {};
		this.events[type] = this.events[type] || [];
		if (this.events[type].contains(fn)) return false;
		else this.events[type].push(fn);
		this.instances.each(function(instance, i){
			instance.addEvent(type, this.check.bind(this, [type, instance, i]));
		}, this);
		return this;
	},

	check: function(type, instance, i){
		this.checker[type][i] = true;
		var every = this.instances.every(function(current, j){
			return this.checker[type][j] || false;
		}, this);
		if (!every) return;
		this.checker[type] = {};
		this.events[type].each(function(event){
			event.call(this, this.instances, instance);
		}, this);
	}

});

var Accordion = Fx.Elements.extend({

	options: {
		onActive: Class.empty,
		onBackground: Class.empty,
		display: 0,
		show: false,
		height: true,
		width: false,
		opacity: true,
		fixedHeight: false,
		fixedWidth: false,
		wait: false,
		alwaysHide: false
	},

	initialize: function(){
		var options, togglers, elements, container;
		$each(arguments, function(argument, i){
			switch($type(argument)){
				case 'object': options = argument; break;
				case 'element': container = $(argument); break;
				default:
					var temp = $$(argument);
					if (!togglers) togglers = temp;
					else elements = temp;
			}
		});
		this.togglers = togglers || [];
		this.elements = elements || [];
		this.container = $(container);
		this.setOptions(options);
		this.previous = -1;
		if (this.options.alwaysHide) this.options.wait = true;
		if ($chk(this.options.show)){
			this.options.display = false;
			this.previous = this.options.show;
		}
		if (this.options.start){
			this.options.display = false;
			this.options.show = false;
		}
		this.effects = {};
		if (this.options.opacity) this.effects.opacity = 'fullOpacity';
		if (this.options.width) this.effects.width = this.options.fixedWidth ? 'fullWidth' : 'offsetWidth';
		if (this.options.height) this.effects.height = this.options.fixedHeight ? 'fullHeight' : 'scrollHeight';
		for (var i = 0, l = this.togglers.length; i < l; i++) this.addSection(this.togglers[i], this.elements[i]);
		this.elements.each(function(el, i){
			if (this.options.show === i){
				this.fireEvent('onActive', [this.togglers[i], el]);
			} else {
				for (var fx in this.effects) el.setStyle(fx, 0);
			}
		}, this);
		this.parent(this.elements);
		if ($chk(this.options.display)) this.display(this.options.display);
	},

	addSection: function(toggler, element, pos){
		toggler = $(toggler);
		element = $(element);
		var test = this.togglers.contains(toggler);
		var len = this.togglers.length;
		this.togglers.include(toggler);
		this.elements.include(element);
		if (len && (!test || pos)){
			pos = $pick(pos, len - 1);
			toggler.injectBefore(this.togglers[pos]);
			element.injectAfter(toggler);
		} else if (this.container && !test){
			toggler.inject(this.container);
			element.inject(this.container);
		}
		var idx = this.togglers.indexOf(toggler);
		toggler.addEvent('click', this.display.bind(this, idx));
		if (this.options.height) element.setStyles({'padding-top': 0, 'border-top': 'none', 'padding-bottom': 0, 'border-bottom': 'none'});
		if (this.options.width) element.setStyles({'padding-left': 0, 'border-left': 'none', 'padding-right': 0, 'border-right': 'none'});
		element.fullOpacity = 1;
		if (this.options.fixedWidth) element.fullWidth = this.options.fixedWidth;
		if (this.options.fixedHeight) element.fullHeight = this.options.fixedHeight;
		element.setStyle('overflow', 'hidden');
		if (!test){
			for (var fx in this.effects) element.setStyle(fx, 0);
		}
		return this;
	},

	display: function(index){
		index = ($type(index) == 'element') ? this.elements.indexOf(index) : index;
		if ((this.timer && this.options.wait) || (index === this.previous && !this.options.alwaysHide)) return this;
		this.previous = index;
		var obj = {};
		this.elements.each(function(el, i){
			obj[i] = {};
			var hide = (i != index) || (this.options.alwaysHide && (el.offsetHeight > 0));
			this.fireEvent(hide ? 'onBackground' : 'onActive', [this.togglers[i], el]);
			for (var fx in this.effects) obj[i][fx] = hide ? 0 : el[this.effects[fx]];
		}, this);
		return this.start(obj);
	},

	showThisHideOpen: function(index){return this.display(index);}

});

Fx.Accordion = Accordion;

/*
Copyright 2005-2007 Netvibes Ltd.
All rights reserved.

Description:
	MooTools 1.1 backward comptability layer for Prototype 1.x.

Notes:
	Hash.toQueryString (obsolete)
*/

var Prototype = {
	Version: '1.5 moocompat',
	ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
	emptyFunction: function() {},
	K: function(x) {return x}
};

Class.create = function() {
	return function() {
		this.initialize.apply(this, arguments);
	}
}

function $_(element) { // $ method: light version
	if (typeof element == 'string')
		element = document.getElementById(element);
	return element;
}

String.prototype.parseJSON = function() {
	//return Json.evaluate(this);
	try {
		return eval('(' + this + ')');
	} catch (e) {
	}
	throw new SyntaxError("parseJSON");
};

Object.clone = function(object) {
	return Object.extend({}, object);
}

// OBSOLETE: conflicts with FF3 native implementation
//document.getElementsByClassName = function(className, parentElement) {
	//return $(parentElement || 'application').getElementsByClassName(className);
//}

// String compat
Object.extend(String.prototype, {

	escapeHTML: function() { // 1.4
		var div = document.createElement('div');
		var text = document.createTextNode(this);
		div.appendChild(text);
		return div.innerHTML;
	},

	unescapeHTML: function() { // 1.4
		var div = document.createElement('div');
		div.innerHTML = this.stripTags();
		return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
	},

	stripTags: function() {
		return this.replace(/<\/?[^>]+>/gi, '');
	},

	stripScripts: function() {
		return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
	},

	extractScripts: function() {
		var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
		var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
		return (this.match(matchAll) || []).map(function(scriptTag) {
			return (scriptTag.match(matchOne) || ['', ''])[1];
		});
	}
});


// Array compat
Object.extend(Array.prototype, {

	inject: function(memo, iterator) {
		this.each(function(value, index) {
			memo = iterator(memo, value, index);
		});
		return memo;
	},

	detect: function(iterator) {
		var result;
		this.each(function(value, index) {
			if (iterator(value, index)) {
				result = value;
				return result;
				//throw $break;
			}
		});
		return result;
	},

	reject: function(iterator) {
		var results = [];
		this.each(function(value, index) {
			if (!iterator(value, index))
				results.push(value);
		});
		return results;
	}
});


// Element compat
Object.extend(Element, {

	getDimensions: function(element) {
		//var position = $(element).getCoordinates();
		//return { width: position.width, height: position.height };

		element = $_(element);
		var display = element.style.display;
		if (display != 'none' && display != null) // Safari bug
		  return {width: element.offsetWidth, height: element.offsetHeight};

		// All *Width and *Height properties give 0 on elements with display none,
		// so enable the element temporarily
		var els = element.style;
		var originalVisibility = els.visibility;
		var originalPosition = els.position;
		var originalDisplay = els.display;
		els.visibility = 'hidden';
		els.position = 'absolute';
		els.display = 'block';
		var originalWidth = element.clientWidth;
		var originalHeight = element.clientHeight;
		els.display = originalDisplay;
		els.position = originalPosition;
		els.visibility = originalVisibility;
		return {width: originalWidth, height: originalHeight};
	},

	visible: function(element) {
		return $_(element).style.display != 'none';
	},

	hide: function(element) { // 66
		element = $_(element);
		element.style.display = 'none';
		return element;
	},

	show: function(element) { // 53
		element = $_(element);
		element.style.display = '';
		return element;
	},

	setStyle: function(element, styles) {
		return $(element).setStyles(styles);
	},

	hasClassName: function(element, className){ // 29
		element = $_(element);
		return element.className.contains(className, ' ');
		//return $(element).hasClass(className);
	},

	addClassName: function(element, className){ // 207
		element = $_(element);
		if (!Element.hasClassName(element, className)) element.className = (element.className + ' ' + className).clean();
		return element;
		//return $(element).addClass(className);
	},

	removeClassName: function(element, className){ // 157
		element = $_(element);
		element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)'), '$1').clean();
		return element;
		//return $(element).removeClass(className);
	},

	remove: function(element) {
		return $(element).remove();
	},

	update: function(element, html) {
		$_(element).innerHTML = html;
	}
});

// Event compat
Object.extend(Event, {
    KEY_BACKSPACE: 8,
    KEY_TAB:       9,
    KEY_RETURN:   13,
    KEY_ESC:      27,
    KEY_LEFT:     37,
    KEY_UP:       38,
    KEY_RIGHT:    39,
    KEY_DOWN:     40,
    KEY_DELETE:   46,
    
	pointerX: function(event) {
		return event.pageX || (event.clientX +
			(document.documentElement.scrollLeft || document.body.scrollLeft));
	},

	pointerY: function(event) {
		return event.pageY || (event.clientY +
			(document.documentElement.scrollTop || document.body.scrollTop));
	},

	element: function(event) {
		return new Event(event).target;
	},

	stop: function(event) {
		new Event(event).stop();
	},

	findElement: function(event, tagName) {
		var element = new Event(event).target;
		while (element.parentNode && (!element.tagName || (element.tagName.toUpperCase() != tagName.toUpperCase())))
			element = element.parentNode; 
		return element;
	},

	observe: function(element, name, observer, useCapture) {
		//App._count ++;
		//console.log(App._count); console.log(element);
		//alert(typeof element);
		element = $_(element);
		if (name == 'keypress' && $defined(window.webkit)) name = 'keydown';
		$(element).addEvent(name, observer);
	},

	stopObserving: function(element, name, observer, useCapture) {
		//App._count --;
		$(element).removeEvent(name, observer);
	}
});

//App._count = 0;

Ajax.Request = new Class({

	initialize: function(url, options) {
		if (options.method) {
			options.method = options.method.toLowerCase();
		}

		if (options.method == "post") {
			options.data = options.parameters;
		} else if (options.parameters) url += "?" + options.parameters;

		if (options.onComplete) {
			this.onCompleteFunction = options.onComplete;
			options.onComplete = this.onComplete.bind(this);
		}

		if (options.onSuccess) {
			this.onSuccessFunction = options.onSuccess;
			options.onSuccess = this.onSuccess.bind(this);
		}

		if (options.onFailure) {
			this.onFailureFunction = options.onFailure;
			options.onFailure = this.onFailure.bind(this);
		}

		this.ajax = new Ajax(url, options).request();
	},

	// MooTools send responseText or responseXML as argument
	// For Prototype compatibility, we send the orignal XMLHttpRquest response object
	onSuccess: function() {
		if (this.onSuccessFunction && this.ajax.isSuccess(this.ajax.transport.status)) {
			this.onSuccessFunction(this.ajax.transport);
		}
	},

	onComplete: function() {
		if (this.onCompleteFunction) {
			this.onCompleteFunction(this.ajax.transport);
		}
	},

	onFailure: function() {
		if (this.onFailureFunction && !this.ajax.isSuccess(this.ajax.transport.status))
			this.onFailureFunction(this.ajax.transport);
	},

	request: function(url) {
		this.ajax.request(url);
	},

	header: function(name) {
		try {
			return this.ajax.transport.getResponseHeader(name);
		} catch (e) { return null; }
	},

	evalJSON: function() {
		try {
			return Json.evaluate(this.ajax.header('X-JSON'));
		} catch (e) { return null; }
	},

	evalResponse: function() {
		try {
			return Json.evaluate(this.ajax.transport.responseText);
		} catch (e) { return null; }
	}

});


$F = function(element) {
	element = $(element);
	if (element.tagName.toLowerCase() == 'select') {
		var index = element.selectedIndex;
		return index >= 0 ? element.options[index].value : null;
	}
	switch (element.type.toLowerCase()) {
		case 'checkbox':
		case 'radio':
			return element.checked ? element.value : null;
		default:
			return element.value;
	}
}

PeriodicalExecuter = new Class({

  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  stop: function() {
    if (!this.timer) return;
    clearInterval(this.timer);
    this.timer = null;
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.callback(this);
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
});


var Form = {
	getElements: function(form) {
		return $(form).getElementsBySelector('input, textarea, select');
	}
}

var Position = {

	cumulativeOffset: function(element) {
		var valueT = 0, valueL = 0;
		do {
			valueT += element.offsetTop  || 0;
			valueL += element.offsetLeft || 0;
			element = element.offsetParent;
		} while (element);
		return [valueL, valueT];
	},

	page: function(forElement) {
		var valueT = 0, valueL = 0;

		var element = forElement;
		do {
			valueT += element.offsetTop  || 0;
			valueL += element.offsetLeft || 0;

			// Safari fix
			if (element.offsetParent == document.body)
			if (element.getStyle('position')=='absolute') break;

		} while (element = element.offsetParent);

		element = forElement;
		do {
			if (!window.opera || element.tagName=='BODY') {
				valueT -= element.scrollTop	 || 0;
				valueL -= element.scrollLeft || 0;
			}
		} while (element = element.parentNode);

		return [valueL, valueT];
	},

	clone: function(source, target) {
		var options = Object.extend({
			setLeft: true,
			setTop: true,
			setWidth: true,
			setHeight: true,
			offsetTop: 0,
			offsetLeft: 0
		}, arguments[2] || {})

		// find page position of source
		source = $(source);
		var p = Position.page(source);

		// find coordinate system to use
		target = $(target);
		var delta = [0, 0];
		var parent = null;
		// delta [0,0] will do fine with position: fixed elements,
		// position:absolute needs offsetParent deltas
		if (target.getStyle('position') == 'absolute') {
			parent = Position.offsetParent(target);
			delta = Position.page(parent);
		}

		// correct by body offsets (fixes Safari)
		if (parent == document.body) {
			delta[0] -= document.body.offsetLeft;
			delta[1] -= document.body.offsetTop;
		}

		// set position
		if (options.setLeft)	  target.style.left	 = (p[0] - delta[0] + options.offsetLeft) + 'px';
		if (options.setTop)	  target.style.top	 = (p[1] - delta[1] + options.offsetTop) + 'px';
		if (options.setWidth)  target.style.width = source.offsetWidth + 'px';
		if (options.setHeight) target.style.height = source.offsetHeight + 'px';
	},

	offsetParent: function(element) {
		if (element.offsetParent) return element.offsetParent;
		if (element == document.body) return element;

		while ((element = element.parentNode) && element != document.body)
		if (element.getStyle('position') != 'static')
			return element;

		return document.body;
	},

	// caches x/y coordinate pair to use with overlap
	within: function(element, x, y) {
		this.xcomp = x;
		this.ycomp = y;
		this.offset = this.cumulativeOffset(element);

		return (y >= this.offset[1] &&
				y <  this.offset[1] + element.offsetHeight &&
				x >= this.offset[0] &&
				x <  this.offset[0] + element.offsetWidth);
	}
};

/*
Copyright 2005-2007 Netvibes Ltd.
All rights reserved.
*/

if (typeof Netvibes == "undefined" || !Netvibes) var Netvibes = {};

if (typeof Netvibes.UI == "undefined" || !Netvibes.UI) Netvibes.UI = {};

/*
Class: Netvibes.UI.TabView

TabView control is used into modules to create tabbed views of content.

XHTML skeleton:
    ><div class="nv-tabSet">
    >  <ul class="nv-tabList">
    >     <li class="tab [selected] [dropped] [disabled]"><a href="javascript:void(0)">Tab one<span class="dropdown"></span></a></li>
    >     <li class="tab"><a href="javascript:void(0)">Tab two</a></li>
    >     <li class="tab"><a href="javascript:void(0)">Tab three</a></li>
    >  <ul>
    >  <div class="nv-tabContent"></div>
    ></div>

Example:
    >var options = { orientation: top, autohideDropdowns: true };
    >var tabs = new Netvibes.UI.TabView();
    >
    >tabView.addTab("TabOne", {text:"Live Search"});
    >tabView.addTab("TabTwo", {text:"Watch"});
    >tabView.addTab("TabWithDropDown", [
    >    {text: "Dropdown item1", xxx: null, yyy: null},
    >    {text: "Dropdown item2", xxx: null, yyy: null},
    >    {text: "Dropdown item3", xxx: null, yyy: null}
    >]);
    >
    >tabView.observe("activeTabChange", onActiveTabChanged);
    >tabView.selectTab("TabOne");
*/

Netvibes.UI.TabView = Class.create();
Netvibes.UI.TabView.prototype = {
  setOptions: function(options) {
      this.options = {
          autohideDropdowns: true,
          tabSetClass: "nv-tabSet",
          tabListClass: "nv-tabList",
          tabContentClass: "nv-tabContent",
          softPadding: false,
          orientation: 'top',
          dataKey: 'text',
          extendedAction: false
      }
      Object.extend(this.options, options || {});
  },
  initialize: function(options) {
      this.setOptions(options);

      this.dataItems = {}; // private map (name => data)
      this.selectedTab = null; // HTMLLiElement
      this.selectedIndex = this.options.selectedIndex || 0;
  },
  _createTabSet: function() {
      this.tabSet = document.createElement("div");
      this.tabSet.className = this.options.tabSetClass;

      this.tabList = document.createElement("ul");
      this.tabList.className = this.options.tabListClass + " autoclear";
      this.tabList.style.padding = '0'; // with autoclear: fix IE6 float escaping bug
      if (/^(top)|(bottom)|(left)|(right)$/.test(this.options.orientation)) {
          Element.addClassName(this.tabList, this.options.orientation);
      }

      this.tabSet.appendChild(this.tabList);
  },
  appendTo: function(element) {
      if (!this.tabSet) this._createTabSet();
      if (!this.selectedTab && this.tabList.hasChildNodes()) this.selectTab(0, false);
      $(element).appendChild(this.tabSet);

      if (window.widget && typeof window.widget.callback == 'function') {
          window.widget.callback('onUpdateBody');
      }
  },

  // labelText, labelIcon, labelTextImage
  addTab: function(name, dataItem, options) {
      if (!this.tabSet) this._createTabSet();
      if (typeof options == 'undefined') options = {}

      var li = document.createElement("li");
      li.className = "tab";
      li.setAttribute("name", name);
      li.onclick = this.eventTabClicked.bindAsEventListener(this);
      if (options.staticText) {
          li.setAttribute('static', 'static');
      }

      var a = document.createElement("a");
      a.href = "#";
      a.target = "_blank";
      a.style.whiteSpace = "nowrap";
      a.onclick = function() { return false; }

      if (dataItem.length) {
          // dropdown item
          if (dataItem[0].image) {
             var imgElement =  document.createElement("img");
             imgElement.src = dataItem[0].image;
             a.appendChild(imgElement);
          } else {
              if (dataItem[0].picto) {
                  var picto = document.createElement("img");
                  picto.src = dataItem[0].picto;
                  picto.style.marginRight = "4px";
                  picto.style.marginBottom = "-2px";
                  a.appendChild(picto);
              } else if (dataItem[0].icon) {
		          var icon = document.createElement("img");
                  icon.src = dataItem[0].icon;
                  icon.style.marginRight = "4px";
                  icon.style.marginBottom = "-2px";
                  a.appendChild(icon);
              }
              var textElement = document.createElement("span");
              textElement.appendChild(document.createTextNode(options.staticText || dataItem[0].text));
              a.appendChild(textElement);
          }
    
          li.setAttribute("key", dataItem[0][this.options.dataKey]);


          var dropdownElement = document.createElement("span");
          dropdownElement.className = "dropdown";
          do {
            var uniqueId = "dropdownTab-" + (++Netvibes.UI._idIncrement);
          } while($(uniqueId))
          dropdownElement.setAttribute("id", uniqueId);

          var placeHolder = document.createElement("img");
          placeHolder.src = "http://" + NV_HOST + "/img/s.gif";
          placeHolder.width = 14;
          placeHolder.height = 14;
          placeHolder.style.verticalAlign = "middle";
          placeHolder.className = "placeHolder";
          dropdownElement.appendChild(placeHolder);
          a.appendChild(dropdownElement);
          dropdownElement.onmousedown = this.eventDropDown.bindAsEventListener(this);
      } else {
          // normal item
          if (dataItem.image) {
             var imgElement =  document.createElement("img");
             imgElement.src = dataItem.image;
             a.appendChild(imgElement);         
          } else {
            
              if (dataItem.picto) {
                  var picto = document.createElement("img");
                  picto.src = dataItem.picto;
                  picto.style.marginRight = "4px";
                  picto.style.marginBottom = "-2px";
                  a.appendChild(picto);
              } else if (dataItem.icon) {
		          var icon = document.createElement("img");
                  icon.src = dataItem.icon;
                  icon.style.marginRight = "4px";
                  icon.style.marginBottom = "-2px";
                  a.appendChild(icon);
              }
            
              a.appendChild(document.createTextNode(dataItem.text));
          }
          li.setAttribute("key", dataItem[this.options.dataKey]);   
      }
      li.appendChild(a);
      if (this.selectedTab == null) {
          //this.selectedTab = a;
      }
      this.tabList.appendChild(li);
      this.createTabContent(name);
      this.dataItems[name] = dataItem;

      return li;
  },
  removeTab: function(name) {
      var tabItem = this.getTab(name);
      Element.remove(tabItem);
  },
  addExternalLink: function(name, href) {
      var tabItem = this.getTab(name);
      tabItem.firstChild.setAttribute("href", href);
  },
  eventTabClicked: function(e) {
      if (Event.element(e).className == "placeHolder") {
          return false;
      }
      var sender = Event.findElement(e, "LI");
      if (!Element.hasClassName(sender, 'disabled')) {
          this.selectTab(sender);
      }
      //Event.stop(e);
      return false;
  },
  eventExtendedActionClicked: function(e) {
      this.hidePopupMenu();
      this._notify('extendedActionClicked');
      return false;
  },
  enableTab: function(name, enable) {
      var tabItem = this.getTab(name);
      if (enable) Element.removeClassName(tabItem, 'disabled');
      else Element.addClassName(tabItem, 'disabled');
  },
  selectTab: function(tabItem, notify) {
      if (typeof tabItem == 'number' || typeof tabItem == 'string') {
          tabItem = this.getTab(tabItem);
      }

      var name = tabItem.getAttribute('name');
      if (this.selectedTab && (this.selectedTab.getAttribute('name') == name)) {
          return; // no changes
      }

      // old active tab
      var items = this.tabList.getElementsByTagName('li');
      for (var i=0, li; li=items[i]; i++) {
          Element.removeClassName(li, 'selected');
          if (this.popupMenu) this.hidePopupMenu();
          if (this.options.autohideDropdowns) {
             var dropdowns = $(li).getElementsByClassName('dropdown');
             $A(dropdowns).each( function(el) {Element.hide(el)} );
          }
      }
      // new active tab
      Element.addClassName(tabItem, 'selected');
      if (this.options.autohideDropdowns) {
          var dropdowns = $(tabItem).getElementsByClassName('dropdown'); 
          $A(dropdowns).each( function(el) {Element.show(el)} );
      }
      for (var i=0, content; content=this.contentArray[i]; i++) {
            // For Safari with iframe content, prevents iframe to be reloaded
            if (Browser.isSafari && content.getElementsByTagName("iframe").length) {
                if (name==content.getAttribute('name')) {
                    content.style.visibility = "visible";
                    content.style.position = "static";
                } else {
                    var frame = content.getElementsByTagName("iframe")[0];
                    content.style.width = frame.contentWindow.innerWidth+"px";
                    content.style.visibility = "hidden";
                    content.style.position = "absolute";
                    content.style.left = "0px";
                    content.style.top = "0px";
                }
            } else {
                if (name==content.getAttribute('name')) Element.show(content); else Element.hide(content);
            }
      }

      this.selectedTab = tabItem;
      this.selectedIndex = tabItem.getAttribute('index');
      if (notify === false) return;
      this._notify('activeTabChange');
  },
  hide: function() {
      Element.hide(this.tabSet);
  },
  show: function() {
      Element.show(this.tabSet);
  },
  hideTabList: function() {
      Element.hide(this.tabList);
  },
  showTabList: function() {
      Element.show(this.tabList);
  },
  reload: function() {
      this._notify('activeTabChange');
  },
  eventDropDown: function(e) {
    var sender = Event.findElement(e, "LI");

    this.popupMenu = $('minitabsOptions');
    if (!this.popupMenu) {
        this.popupMenu = document.createElement('ul');
        this.popupMenu.setAttribute('id', 'minitabsOptions');
        this.popupMenu.className = 'popupMenu';
        this.popupMenu.style.position = 'absolute';
        document.getElementsByTagName('body').item(0).appendChild(this.popupMenu);
        Element.hide(this.popupMenu);
        Event.observe(document, 'mousedown', this.hidePopupMenu.bindAsEventListener(this)); // free on window.unload
    }
    var dropdownButton = $(sender).getElementsByClassName('dropdown')[0];
    if (Element.visible(this.popupMenu) && this.popupMenu.getAttribute("dropdownId") == dropdownButton.id) {
        this.hidePopupMenu();
        return;
    }

    this._showPopupMenu(sender);
    this.popupMenu.setAttribute("dropdownId", dropdownButton.id);

    Event.stop(e);
    return false;
  },
  getTabContent: function(name) {
      if (typeof name == 'number') {
          return this.contentArray.detect( function(el) {return el.getAttribute("index") == name;} );
      }
      return this.contentArray.detect( function(el) {return el.getAttribute("name") == name;} );
  },
  setContent: function(name, content) {
      var node = this.getTabContent(name);
      if (node) {
          if (typeof content == 'string') {
              node.innerHTML = content;
          } else {
              node.innerHTML = '';
              node.appendChild(content);
          }
      }
      if (window.widget && typeof window.widget.callback == 'function') {
          window.widget.callback('onUpdateBody');
      }
  },
  getTab: function(name) { // Returns HTMLLiElement
      if (typeof name == 'string' || typeof name == 'number') {
          var items = this.tabList.getElementsByTagName('li');
          for (var i=0, item; item=items[i]; i++) {
              // Retrieves tab by index
              if (typeof name == 'number' && name == i) return item;
              // Retrieves tab by name
              if (name == item.getAttribute('name')) return item;
          }
      }
      return name; // object
  },
  observe: function(name, observer) { // onchange
      if (!this.observers) this.observers = [];
      this.observers.push([name, observer]);
  },
  _notify: function(event) {
      if (!this.observers) return;

      var sender = this.selectedTab;
      var eventArgs = this.dataItems[sender.getAttribute('name')];
      if (eventArgs.length) {
          var dataKey = this.options.dataKey;
          eventArgs = eventArgs.detect(function(el) { return el[dataKey] == sender.getAttribute('key')});
      }
      this.observers.each(function(observer) {
          if (observer[0] == event && typeof(observer[1]) == 'function')
              observer[1](sender.getAttribute('name'), eventArgs);
      });
  },
  _showPopupMenu: function(tabItem) {
      var offset = Position.cumulativeOffset(tabItem);

      this.popupMenu.innerHTML = '';
      try {
          var tabName = tabItem.getAttribute('name');
          var dataItems = this.dataItems[tabName];
          var tabKey = tabItem.getAttribute('key');
          for (var i=0, item; item=dataItems[i]; i++) {

              //do not display the current selected item
              if (item[this.options.dataKey] == tabKey && tabItem.getAttribute('static') != 'static')
                  continue;

              var li = document.createElement("li");
              var a = document.createElement("a");
              if (item.picto) {
                  var picto = document.createElement("img");
                  picto.src = item.picto;
                  picto.style.marginRight = "4px";
                  picto.style.marginBottom = "-2px";
                  a.appendChild(picto);
              } else if (item.icon) {
                  var icon = document.createElement("img");
                  icon.src = item.icon;
                  icon.style.marginRight = "4px";
                  icon.style.marginBottom = "-2px";
                  a.appendChild(icon);
              }
              a.href = (item.htmlUrl || "javascript:void(0)");
              a.setAttribute('context', tabName);
              a.appendChild(document.createTextNode(item.text));
              a.setAttribute("key", item[this.options.dataKey]);
              if (!this.options.extendedAction && (dataItems.length -1) == i) {
                  Element.addClassName(a, 'last');
              }
              a.onclick = this.eventPopupMenuClicked.bindAsEventListener(this);
              li.appendChild(a);
              this.popupMenu.appendChild(li);
          }
          
          if (this.options.extendedAction) {
              var li = document.createElement("li");
              var a = document.createElement("a");
              a.href = "javascript:void(0)";
              Element.addClassName(a, 'action');
              a.setAttribute('context', tabName);
              a.appendChild(document.createTextNode(this.options.extendedAction));
              a.onclick = this.eventExtendedActionClicked.bindAsEventListener(this);
              li.appendChild(a);
              this.popupMenu.appendChild(li);
          }
          
      } catch(e) {}

      var tabDimensions = Element.getDimensions(tabItem);

      //.moduleFrame {border: 1px solid #889DFF;
      var delta = (typeof App != 'undefined' && App.userCustom && (App.userCustom.themeTitle == 'Coriander'))? 0 : 1;
      if (Browser.isSafari || Browser.isOpera) delta = 0;

      this.popupMenu.style.left = (offset[0] + delta)+'px';
      this.popupMenu.style.top  = (offset[1] + delta + tabDimensions.height)+'px'; // 24: IE, Opera

      // Ensures popup's min-width is the width of the tab
      this.popupMenu.style.width = "auto";
      var menuWidth = Element.getDimensions(this.popupMenu).width;
      if (menuWidth < tabDimensions.width) {
         var delta = 12;
         if (Browser.isIE) delta = 11;
         this.popupMenu.style.width = tabDimensions.width-delta + "px";
      }

      Element.show(this.popupMenu);
      var drops = $(this.tabList).getElementsByClassName("dropped");
      $A(drops).each(function(el) {
          Element.removeClassName(el, "dropped");
      });
      Element.addClassName(tabItem, 'dropped'); // state ON
      if (window.widget && typeof window.widget.callback == 'function') {
		// as our iframed widget may too short to display the dropdown,
		// we'll need to resize widget.body to show the whole dropdown popup div
		// so, get some dimensions and positions
		var item; var dim;
		item = widget.body; var bodyTop = 0; while (item && item != document.body) { bodyTop += item.offsetTop; item = item.offsetParent; }
		item = this.popupMenu; var popupTop = 0; while (item && item != document.body) { popupTop += item.offsetTop; item = item.offsetParent; }
		popupDim = Element.getDimensions(this.popupMenu);
		bodyDim = widget.body.getDimensions();
		// popupHeight is the ideal widget.body height for displaying the whole dropdown
		var popupHeight = popupTop - bodyTop + popupDim.height;
		// if widget.body is shorter than the best height (dropdown doesn't fit into the iframe)
		// let't resize widget.body to the proper height
		if (bodyDim.height < popupHeight) {
		  widget.body.style.height = popupHeight + 'px';
		}
	    window.widget.callback("onUpdateBody");
	  }
  },
  eventPopupMenuClicked: function(e) {
      var sender = Event.findElement(e, "A");
      var tabName = sender.getAttribute('context');

      var tabItem = this.getTab(tabName);
      if (tabItem.getAttribute('static') != 'static') {
          var dataKey = this.options.dataKey;
          var dataItem = this.dataItems[tabName].detect(function(el) { return el[dataKey] == sender.getAttribute('key')});
          tabItem.getElementsByTagName("span")[0].innerHTML = dataItem.text;
          if (dataItem.picto) {
              tabItem.getElementsByTagName("img")[0].src = dataItem.picto;
          } else if (dataItem.icon) {
              tabItem.getElementsByTagName("img")[0].src = dataItem.icon;
          }
      }

      tabItem.setAttribute("key", sender.getAttribute('key'));
      this._notify('activeTabChange');

      this.selectTab(tabItem);
      this.hidePopupMenu();

      Event.stop(e);
      return false;
  },
  selectKey: function(name, key, select) {
       var tabItem = this.getTab(name);
       var dataItem = null;
       var dataKey = this.options.dataKey;
       if (typeof (this.dataItems[name].detect) == 'function') {
           dataItem = this.dataItems[name].detect(function(el) { return el[dataKey] == key; });
       }
       if (dataItem) {
           tabItem.getElementsByTagName("span")[0].innerHTML = dataItem.text;
           tabItem.setAttribute("key", key);
           if (dataItem.icon) {
               tabItem.getElementsByTagName("img")[0].src = dataItem.icon;
           }
           if (select === undefined || select) {
               this.selectTab(tabItem); // Select by default
           }
           if (select === undefined || select) {
               this.selectTab(tabItem); // Select by default
           }
       }
  },
  hidePopupMenu: function(e) {
      if (!this.popupMenu)
          return false;

      // DOM Level1
      if (e && Position.within(this.popupMenu, Event.pointerX(e), Event.pointerY(e))) {
          Event.stop(e);
          return false;
      }
      Element.hide(this.popupMenu);
      var drops = $(this.tabList).getElementsByClassName("dropped");
      $A(drops).each(function(el) {
          Element.removeClassName(el, "dropped");
      });
      if (window.widget && typeof window.widget.callback == 'function') {
		// resetting widget.body height
	    widget.body.style.height = '';
	    window.widget.callback("onUpdateBody");
	  }
  },
  createTabContent: function(name, index) {
      var tabContent = document.createElement("div");
      if (this.options.softPadding) {
          if (Browser.isIE) tabContent.style.padding = "3px 3px 3px 3px";
          else tabContent.style.padding = "6px 3px 3px 3px";
      }
      tabContent.className = this.options.tabContentClass;
      tabContent.setAttribute("name", name);
      tabContent.innerHTML = _("Loading...");
      //tabContent.style.display = "none";
      //tabContent.style.visibility = "hidden";
      this.tabSet.appendChild(tabContent);

      if (!this.contentArray) this.contentArray = [];
      this.contentArray.push(tabContent);
      tabContent.setAttribute("tabIndex", this.contentArray.length-1);
  },
  restoreState: function(module) {
      var data = module.dataObj.data;

      if (typeof data.miniTabViewState != 'undefined') {
          var state = data.miniTabViewState.parseJSON();
          if (state && typeof state.selectedKey == 'string') {
              this.selectKey(state.selectedKey);
              return;
          }
          if (state && typeof state.selectedTab == 'string') {
              this.selectTab(state.selectedTab);
              return;
          }
      }
      // By default, select first tab
      this.selectTab(0);
  },
  saveState: function(module) {
      var jsonViewState = null;
      var selectedKey = this.selectedTab.getAttribute('key');
      if (typeof selectedKey == 'string') {
          jsonViewState = '{"selectedKey": "'+selectedKey+'"}';
      } else {
          jsonViewState = '{"selectedTab": "'+this.selectedTab.getAttribute('name')+'"}';
      }
      if (jsonViewState && jsonViewState != module.dataObj.data.miniTabViewState) {
          module.dataObj.data.miniTabViewState = jsonViewState;
          module.save();
      }
  },
  destroy: function() {
      Event.stopObserving(document, 'mousedown', this.hidePopupMenu);
  }
}

var MiniTabs = {}; // factory
MiniTabs.create = function(element, options) {
    var tabs = new Netvibes.UI.TabView(options);
    tabs.appendTo(element);
    return tabs;
}

/*
Copyright 2005-2007 Netvibes Ltd.
All rights reserved.
*/

/*
Class: Netvibes.UI.FlashPlayer

Flash player with full screen capabilities. Currently used by video module.

Example:
	>var flashPlayer = new Netvibes.UI.FlashPlayer(moduleContent);
	>
	>flashPlayer.show('http://video.google.com/googleplayer.swf?docId=39288702201978303');
	>
	>flashPlayer.setFullScreenMode(true);
*/
Netvibes.UI.FlashPlayer = Class.create();
Netvibes.UI.FlashPlayer._maxzIndex = 9010;
Netvibes.UI.FlashPlayer.prototype = {
  setOptions: function(options) {
      this.options = { flashVars: '', flashUrl: '', width: 320, height: 240,
                       wmode: "opaque", showToolbar: true, showFullScreenLink: true,
                       fixModuleId: 0 }
      Object.extend(this.options, options || {});
  },
  initialize: function(parent, options) {
      this.setOptions(options);
      this.parent = parent;
      this.container = null;
      this.linuxIframe = null;
      this.isFullScreen = false;
  },
  show: function(flashUrl, flashVars, options) {
      if (typeof options == 'undefined') options = {}

      this.options.flashUrl = flashUrl; // ie, googleplayer.swf
      this.options.flashVars = flashVars;

      if (!this.container) {
          this.container = document.createElement("div");
          this.container.className = "flashplayer";
          this.container.align = 'center';
          this.container.style.position = "absolute";
          this.container.style.zIndex = '8000';
          this.container.style.background = "#ffffff";
          this.parent.appendChild(this.container);

          if (!Browser.isIE) {
              // IE is buggy with position: absolute|relative (block may disappear)
              this.container.style.position = "absolute";

              // Preserve space for absolute positionned container
              this.placeHolder = document.createElement("div");
              this.placeHolder.style.height = this.options.height+"px";
              this.parent.appendChild(this.placeHolder);
          }
      } else {
          this.container.innerHTML = "";
      }

      var playerHtml = '';
      playerHtml += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+this.options.width+'" height="'+this.options.height+'">';
      playerHtml +=   '<param name="allowScriptAccess" value="sameDomain" />';
      playerHtml +=   '<param name="movie" value="'+this.options.flashUrl+'" />';
      playerHtml +=   '<param name="quality" value="high" />';
      playerHtml +=   '<param name="wmode" value="'+this.options.wmode+'" />';
      playerHtml +=   '<param name="bgcolor" value="#ffffff" />';
      playerHtml +=   '<param value="true" name="allowfullscreen"/>';
      playerHtml +=   '<param name="flashVars" value="'+this.options.flashVars+'" />';
      playerHtml +=   '<embed wmode="'+this.options.wmode+'" src="'+this.options.flashUrl+'" quality="high" bgcolor="#ffffff" width="'+this.options.width+'" height="'+this.options.height+'" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashVars="'+this.options.flashVars+'" allowfullscreen="true"/>';
      playerHtml += '</object>';

      this.container.innerHTML = playerHtml;

      // Fix useless because the object is inserted by JavaScript
      //if (Browser.isIE) {
          // ByPass IE: "click to activate and use this control" (KB912945)
          //var object = this.parent.getElementsByTagName("object")[0];
          //object.outerHTML = object.outerHTML; // warning: this will de-reference any reference
      //}
      this.element = this.parent.getElementsByTagName((Browser.isIE || Browser.isSafari)? "object" : "embed")[0];

      if (this.options.showToolbar) this._createLinks(options.mediaLinkUrl, options.mediaLinkText);

      Element.show(this.container);
      if (this.placeHolder) Element.show(this.placeHolder);
      this.resize();
  },
  hide: function() {
      if (this.container) {
          this.container.innerHTML = ''; // Needed for IE in order to stop playing
          Element.hide(this.container);
          if (this.placeHolder) Element.hide(this.placeHolder);
      }
      if (this.hide && this.links) {
          Element.hide(this.links);
      }
	  if (window.widget) { window.widget.callback("onUpdateBody"); }
      return false;
  },
  setFullScreenMode: function(mode) {
      this.isFullScreen = (typeof(mode)!='undefined' && mode) ? true : false;
      this._fixAdjacentModules();

      if (this.isFullScreen) {
          if (App.Sidebar.isOpen())
              App.Sidebar.close();

          window.scrollTo(0, 0);
          if (Browser.isIE) this.container.style.position = 'absolute';
          this.container.style.top = "0px";
          this.container.style.left = "0px";
          this.container.style.marginLeft = '0';

          // always make the full screen video as the highest zIndex
          // preserves others videos with the same zIndex the overlay it
          this.container.style.zIndex = ++Netvibes.UI.FlashPlayer._maxzIndex;
          this._createCloseButton();

          // ByPass App 'resize' notifications limiter
          Event.observe(window, 'resize', this.resize.bindAsEventListener(this));
      } else {
          Element.remove(this.closeButton);
          if (Browser.isLinux && Browser.isFirefox) Element.remove(this.linuxIframe);
          Event.stopObserving(window, 'resize', this.resize);
      }
      // Computes size
      this.resize();

      // Hack for Firefox on Linux to show the "Back to your page" button
      if (Browser.isLinux && Browser.isFirefox) {
          this.linuxIframe = document.createElement("iframe");
	      this.linuxIframe.style.position = "absolute";
          this.linuxIframe.style.width = this.closeButton.offsetWidth+"px";
          this.linuxIframe.style.height = this.closeButton.offsetHeight+"px";
	      this.linuxIframe.style.left = this.closeButton.offsetLeft+"px";
          this.linuxIframe.style.top = this.closeButton.offsetTop+"px";
	      this.linuxIframe.setAttribute("frameborder", "0");
	      this.linuxIframe.setAttribute("scrolling", "no");
          this.linuxIframe.style.zIndex = parseInt(this.container.style.zIndex)+1;
          document.body.appendChild(this.linuxIframe);
      }
      
      return false;
  },
  resize: function(w, h) {

      if (!this.container) return;

      if (this.isFullScreen) {
          if (this.container.style.width != Browser.getDocumentWidth()) {

              // Helps to computes the correct document width
              this.container.style.width = '1px';
              this.container.style.height = '1px';
              this.element.style.width = '1px';

              this.container.style.width = Browser.getDocumentWidth()+'px';
              this.container.style.height = Browser.getDocumentHeight()+'px';
              this.element.style.height = Browser.getClientHeight()-(Browser.isFirefox? 3 : 0)+'px';
              this.element.style.width = Browser.getDocumentWidth()+'px';
          }
          return;
      }

      // Reset container position
      this.container.style.top = '';
      this.container.style.left = '';
      this.container.style.width = '1px';
      this.container.style.height = '1px';
      
      if (typeof w != "undefined" && typeof h != "undefined") {
            this.container.style.width = w+'px';
            if (!Browser.isIE) {
                this.placeHolder.style.height = h+"px";
                this.container.style.marginLeft = '0px';
            }
            this.container.style.height = h+"px";
            this.element.style.width = w+'px';
            this.element.style.height = h+"px";
            return ;
      }
      
      if (Browser.isIE) {
          this.container.style.position = '';
          var availableSpace = Element.getDimensions(this.parent);
          this.container.style.width = availableSpace.width+'px';
          this.container.style.height = this.options.height+'px';
          this.element.style.width = this.options.width+'px';
          this.element.style.height = this.options.height+'px';
      } else {
          // Align center horizontally
          var availableSpace = Element.getDimensions(this.placeHolder);
          var width = Math.min(this.options.width, availableSpace.width);
          this.container.style.width = width+'px';
          this.container.style.height = availableSpace.height+'px';
          this.element.style.width = width+'px';
          this.element.style.height = availableSpace.height+'px';
          this.container.style.marginLeft = Math.round((availableSpace.width-width)/2)+'px';
      }
  },
  _createCloseButton: function() {
      this.closeButton = document.createElement("input");
      this.closeButton.type = "button";
      this.closeButton.id = "flashplayer-back";
      this.closeButton.style.position = "absolute";
      this.closeButton.style.top = "2px";
      this.closeButton.style.right = "2px";
      this.closeButton.value = _("Back to my page");
      this.closeButton.style.zIndex = parseInt(this.container.style.zIndex)+2;
      // Fix for IE7 only: width required
      if (Browser.isIE && Browser.version > 6) {
          this.closeButton.style.width = (this.closeButton.value.length)+"em";
      }
      this.closeButton.onclick = function() {
          this.setFullScreenMode(false);
      }.bind(this);

      document.body.appendChild(this.closeButton);
  },
  _createLinks: function(linkUrl, linkText) {
      if (this.links) Element.remove(this.links);

      this.links = document.createElement("p");
      this.links.align = 'center';
      this.links.style.padding = '4px';

      if (this.options.showFullScreenLink) {
        var linkFullScreen = document.createElement("a");
        linkFullScreen.href = "javascript:void(0)";
        linkFullScreen.onclick = this.setFullScreenMode.bindAsEventListener(this);
        linkFullScreen.innerHTML = _("Full screen");
        this.links.appendChild(linkFullScreen);
        this.links.appendChild(document.createTextNode(' | '));
      }

      if (linkUrl && linkText) {
          var linkOriginal = document.createElement("a");
          linkOriginal.href = linkUrl;
          linkOriginal.rel = 'external';
          linkOriginal.target = '_blank';
          linkOriginal.innerHTML = linkText.stripTags();
          this.links.appendChild(linkOriginal);
      }

      this.links.appendChild(document.createTextNode(' | '));
      var linkClose = document.createElement("a");
      linkClose.href = "javascript:void(0)";
      linkClose.onclick = this.hide.bind(this);
      linkClose.innerHTML = _("Hide");

      this.links.appendChild(linkClose);
      this.parent.appendChild(this.links);
  },
  // Fixes FF/Opera rendering z-index issue with flash
  // Used to stop others videos running too (all browsers)
  _fixAdjacentModules: function() {
      if (!this.options.fixModuleId) return;

      // Hide/restore column resizer background-image
      var columnGrippers = $('application').getElementsByClassName("gripper");
      for (var i=0;  i < columnGrippers.length; i++) {
          var gripper = columnGrippers[i];
          if (this.isFullScreen) gripper.style.visibility="hidden"; else gripper.style.visibility="";
      }
      // Hide/restore modules
      for (var i=0, module; module=App.moduleList[i]; i++) {
          if (module.dataObj.tab == App.selectedTab && module.dataObj.fixId != this.options.fixModuleId) {
              if (this.isFullScreen) module.completeHide(); else module.tabBuild();
          }
      }

      // Hide/restore the wizard if displayed
      if (this.isFullScreen && Element.visible('wizard')) {
         Element.hide('wizard');
         this.options.shouldDisplayWizard = true;
      } else if (this.options.shouldDisplayWizard == true) {
         Element.show('wizard');
         delete this.options.shouldDisplayWizard;
      }
      // Hide/restore the info box if displayed
      if (this.isFullScreen && Element.visible('infoBox')) {
         Element.hide('infoBox');
         this.options.shouldDisplayInfoBox = true;
      } else if (this.options.shouldDisplayInfoBox == true) {
         Element.show('infoBox');
         delete this.options.shouldDisplayInfoBox;
      }
  }
}

/*
Copyright 2005-2007 Netvibes Ltd
All rights reserved.
Author : François HODIERNE
*/

if (typeof Netvibes == "undefined" || !Netvibes) var Netvibes = {};

if (typeof Netvibes.UI == "undefined" || !Netvibes.UI) Netvibes.UI = {};

Netvibes.UI.PrefsForm = function(params) {

    /* Property: module

    *Module*: the module using the current Preference form.
    */
    this.module = params.module;
  
    /* Property: displayButton

    *Type*: ..
    */
    this.displayButton = params.displayButton;

}

Netvibes.UI.PrefsForm.prototype = {
   
  /* Property: controls

  *Collection{String->Function}*: associates the name of a control with the method creating the control.

  Those controls are used to give a "type" to the form widgets.

  Available controls are:
  * default: generates a standard text input,
  * boolean: generates a checkbox,
  * password: generates a password input,
  * textarea: generates a text area,
  * range: generates a dropdown list.
  
  */ 
  controls: {

    'default': function(pref) {
      var value = this.module.getValue(pref.name);
      if(!value || value == 'null') value = ''; // why string null ?
      var input = this.module.createElement('input');
      input.type = "text";
      input.value = value;
      input.id = 'm_' + this.module.id + '_' + pref.name;
      input.name = pref.name;
      return input;
    },
    'boolean': function(pref) {
      var input = this.module.createElement('input');
      input.type = "checkbox";
      input.id = 'm_' + this.module.id + '_' + pref.name;
      input.name = pref.name;
      if(this.module.getBool(pref.name) === true) {
        input.setAttribute('checked', 'checked');
        input.defaultChecked = true; // for IE
      }
      if(pref.onchange) {
        input.onclick = ( function(e) {
          var sender = (e.target || e.srcElement);
          if(sender.checked == true) this.module.setValue(pref.name, 'true');
          else this.module.setValue(pref.name, 'false');
          this.module.callback(pref.onchange);
        } ).bindAsEventListener(this);
      }
      return input;
    },
    'password': function(pref) {
      var input = '<input type="password" value="" id="m_' + this.module.id + '_pass" name="pass" /> ';
      return input;
    },
    'textarea': function(pref) {
      if(this.module.getValue(pref.name)) var value = this.module.getValue(pref.name); else var value = '';
      var textarea = '<textarea id="m_' + this.module.id + '_' + name + '" name="' + pref.name + '">' + value + '</textarea> ';
      return textarea;
    },
    'range': function(pref) {
      var select = this.module.createElement('select');
      select.id = 'm_' + this.module.id + '_' + pref.name;
      select.name = pref.name;
      if (parseInt(pref.step) > 0) {
	      for(var i=parseInt(pref.min); i<=parseInt(pref.max); i+=parseInt(pref.step)) {
	        var option = this.module.createElement('option');
	        if(this.module.getValue(pref.name) == i) option.setAttribute('selected', 'selected');
	        option.value = i; option.setText(i);
	        select.appendChild(option);
	      }
      }
      if(pref.onchange) {
        select.onchange = ( function(e) {
          var sender = (e.target || e.srcElement);
          this.module.setValue(pref.name, sender.value)
          this.module.callback(pref.onchange);
        } ).bindAsEventListener(this);
      }
      return select;
    },
    'list': function(pref) {
      var select = this.module.createElement('select');
      select.id = 'm_' + this.module.id + '_' + pref.name;
      select.name = pref.name;
      for(var i=0; i<pref.options.length; i++) {
        var option = this.module.createElement('option');
        if(this.module.getValue(pref.name) == pref.options[i].value) option.setAttribute('selected', 'selected');
        option.value = pref.options[i].value;
        option.setText( (pref.options[i].label ? pref.options[i].label : pref.options[i].value ) );
        select.appendChild(option);
      }
      if(pref.onchange) {
        select.onchange = ( function(e) {
          var sender = (e.target || e.srcElement);
          this.module.setValue(pref.name, sender.value)
          this.module.callback(pref.onchange);
        } ).bindAsEventListener(this);
      }
      return select;
    },
    'color': function(pref) {
      if(typeof pref.colors == "undefined")
        pref.colors = ['white', 'yellow', 'green', 'red', 'blue', 'orange'];
      var colorSelector = this.module.createElement('div');
      colorSelector.addClassName('postItcolorSelection');
      for(i=0; i<pref.colors.length;i++) {
        var color = this.module.createElement('div');
        //color.addClassName(colors[i]);
        color.setStyle('background-color', pref.colors[i]);
        color.onclick = ( function(e) {
          var sender = (e.target || e.srcElement);
          this.module.setValue(pref.name, sender.style.backgroundColor);
          if(pref.onchange) this.module.callback(pref.onchange);
        } ).bindAsEventListener(this);
        colorSelector.appendChild(color);
      };
      return colorSelector;
    }
  
  },

  /* Method: getContent

  Gets the content of the preference form, for display.

  Parameters:
  * None.
  
  Returns:
  * String: the HTML version of the preference form.
  */
  getContent: function() {
    
    var editContent = '';
    
    this.form = this.module.createElement("form");
     
    var table = this.module.createElement("table");
    table.addClassName("formTable");
    table.setStyle('width', '100%');
    
    var tbody = this.module.createElement("tbody");
    
    for(var i = 0; i < this.module.preferences.length; i++) {
      
      var tr = this.module.createElement("tr");
      var pref = this.module.preferences[i];
      
      if(pref.type == 'hidden') continue;
      
      if(!pref.label) pref.label = pref.name;
      var label = this.module.createElement("label");
      label.setAttribute('for', 'm_' + this.module.id + '_' + pref.name);
      label.setHTML( _(pref.label+':') );
      var tdl = this.module.createElement("td");
      tdl.appendChild(label);
      tr.appendChild(tdl);
      
      if(!this.controls[pref.type]) pref.type = 'default';
      var control = this.controls[pref.type].bind(this)(pref);
      var tdc = this.module.createElement("td");
      
      tdc.setContent(control);
      tr.appendChild(tdc);
      
      tbody.appendChild(tr);
      
    }
    
    if(this.displayButton == undefined || this.displayButton === true) {
      var submit = this.module.createElement('input');
      submit.type = 'submit';
      submit.value = _("Ok");
      submit.addClassName('buttonClean');
      var tr = this.module.createElement("tr");
      var tds = this.module.createElement("td");
      tds.colSpan = '2';
      tds.appendChild(submit);
      tr.appendChild(tds);
      tbody.appendChild(tr);
    }
    
    table.appendChild(tbody);
    
    this.form.appendChild(table);
    
    this.form.onsubmit = ( function() {
      var callback = ( function() { this.callback('endEdit') } ).bind(this.module);
      this.saveValues();
      // force to saveValues immediatly and add a callback when it's done
      this.module.saveValues(callback);
      return false;
    } ).bindAsEventListener(this);
    
    return this.form;
    
  },
  
  /* to document */
  saveValues: function(form) {
    
    if(typeof form == 'undefined') var form = this.form;

    var formElements = UWA.Form.getElements(form);

    for (var j = 0; j < formElements.length; j++) {
      var el = formElements[j];
      if(el.type == "submit") continue;
      switch(el.type) {
        case 'password':
          if(el.value != '' && el.value != 'XXNVXX' )
            this.module.setValue(el.name, el.value)
          break;
        case 'checkbox':
          if(el.checked) this.module.setValue(el.name, 'true');
          else this.module.setValue(el.name, 'false');
          break;  
        case 'radio':
          if(el.checked)
            this.module.setValue(el.name, el.value);
          break;
        default :
          this.module.setValue(el.name, el.value);
        break;
      }
    }
    
  }

}

/*
Copyright 2005-2007 Netvibes Ltd
All rights reserved.
Author : François HODIERNE
*/

if (typeof Netvibes == "undefined" || !Netvibes) var Netvibes = {};

if (typeof Netvibes.UI == "undefined" || !Netvibes.UI) Netvibes.UI = {};


Netvibes.UI.PageBuilder = Class.create();

Netvibes.UI.PageBuilder.prototype = {
  setOptions: function(options) {
      this.options = {
          nextText: _("next"),
          previousText: _("previous"),
          nextImageUrl: null,
          nextImageDisabledUrl: null,
          prevImageUrl: null,
          prevImageDisabledUrl: null,
          dataArray: [],
          perPage: 5,
          offset: 0,
          compactMode: true
      }
      Object.extend(this.options, options || {});

      this.perPage = parseInt(this.options.perPage);
      this.offset = parseInt(this.options.offset);
  },
  initialize: function(options) {
      this.setOptions(options);
      this.dataArray = this.options.dataArray;

      this.preload = [];
      if (this.options.nextImageDisabledUrl && this.options.prevImageDisabledUrl) {
          this.preload["nextImageDisabledUrl"] = new Image();
          this.preload["nextImageDisabledUrl"].src = this.options.nextImageDisabledUrl;
          this.preload["prevImageDisabledUrl"] = new Image();
          this.preload["prevImageDisabledUrl"].src = this.options.prevImageDisabledUrl;
      }
  },
  appendTo: function(element) {
      var element = $(element);
      this.build(element);
      this.eventPageChanged();
  },
  build: function(container) {
      if (!this.options.compactMode) {
          container.className = "nv-pager";
      }

      // Previous page link
      this.prev = document.createElement("a");
      this.prev.className = 'prev';
      this.prev.setAttribute('hidefocus', 'hidefocus');
      this.prev.href = 'javascript:void(0)';
      this.prev.innerHTML = this.options.prevImageUrl? '<img src="'+this.options.prevImageUrl+'" alt="" />' : this.options.previousText;
      this.prev.onclick = this.eventPageChanged.bindAsEventListener(this);

      // Next page link
      this.next = document.createElement("a");
      this.next.className = 'next';
      this.next.setAttribute('hidefocus', 'hidefocus');
      this.next.href = 'javascript:void(0)';
      this.next.innerHTML = this.options.prevImageUrl? '<img src="'+this.options.nextImageUrl+'" alt="" />' : this.options.previousText;
      this.next.onclick = this.eventPageChanged.bindAsEventListener(this);

      this.prev.className = (this.offset > 0)? 'prev' : 'prev disabled';
      this.next.className = (this.offset < this.dataArray.length - this.perPage)? 'next' : 'next disabled';

      container.appendChild(this.prev);
      container.appendChild(this.next);
  },
  eventPageChanged: function(e) {
      var sender = (e && Event.findElement(e, "A"));
      if (sender && Element.hasClassName(sender, 'disabled')) {
          return false;
      }
      if (sender && Element.hasClassName(sender, 'prev')) {
          this.offset = this.offset - this.perPage;
      }
      else if (sender && Element.hasClassName(sender, 'next')) {
          this.offset = this.offset + this.perPage;
      }
      var event = {};
      event.items = this.dataArray.slice(this.offset, this.offset + this.perPage);
      event.offset = this.offset;
      event.currentPage = -1; // not yet implemented
      event.totalPage   = -1; // not yet implemented

      this.prev.className = (this.offset > 0)? 'prev' : 'prev disabled';
      this.next.className = (this.offset < this.dataArray.length - this.perPage)? 'next' : 'next disabled';
      this.updateState();

      if (typeof this.onchange == 'function')
          this.onchange(event);

      return false;
  },
  updateState: function() {
      if (this.options.prevImageUrl) {
          this.prev.firstChild.src = Element.hasClassName(this.prev, 'disabled')? 
              this.options.prevImageDisabledUrl : this.options.prevImageUrl;
      }
      if (this.options.nextImageUrl) {
          this.next.firstChild.src = Element.hasClassName(this.next, 'disabled')? 
              this.options.nextImageDisabledUrl : this.options.nextImageUrl;
      }
  }
}

Netvibes.UI.Pager = function(params) {

      this.module = params.module;
      this.limit = parseInt(params.limit);
      this.offset = parseInt(params.offset);
      this.callback = params.callback;
      this.dataArray = params.dataArray;
      
}

Netvibes.UI.Pager.prototype = {
  
  getContent: function() {

    var pager = document.createElement("div");
    pager.className = 'nv-pager';
		
		if (this.offset > 0) {
		  var prev = document.createElement("a");
		  prev.className = 'prev';
		  prev.href = '#';
		  prev.innerHTML = _("prev");
		  prev.onclick = ( function() {
		    this.onChange(this.offset - this.limit);
		    return false;
		  } ).bind(this);
      pager.appendChild(prev);
		}
		
		if (this.offset < this.dataArray.length - this.limit ) {
		  var next = document.createElement("a");
		  next.className = 'next';
		  next.href = '#';
		  next.innerHTML = _("next");
		  next.onclick = ( function() {
		    this.onChange(this.offset + this.limit);
		    return false;
		  } ).bind(this);
      pager.appendChild(next);	
		}
		
		// fix a problem with float on the bottom of the module when calculating innerHeight
		var fix = document.createElement("div");
		fix.innerHTML = '<p style="padding:0;margin:0;line-height:0;height:0;clear:both"></p>';
		pager.appendChild(fix);

    return pager;

  },
  
  /* retro compatibility */
  getDom: function() { this.getContent() }

}

if (typeof Netvibes == "undefined" || !Netvibes) var Netvibes = {};

if (typeof Netvibes.DLA == "undefined" || !Netvibes.DLA) Netvibes.DLA = {};

/*
Class: Netvibes.DLA.SearchForm

Pretty in Opera too ;)

Example:
    >var options = { showCheckbox: true };
    >
    >var searchForm = new Netvibes.UI.SearchForm(options);
    >
    >searchForm.setInitialState(favicon, text, checked);
    >searchForm.observe('submit', function(searchText, [checked]) { ... });
    >searchForm.observe('reset', function(searchText, [checked]) { ... });
    >searchForm.observe('toggle', function(searchText) { ... });
    >
    >searchForm.appendTo(moduleContent);
*/


Netvibes.DLA.SearchForm = function(options) {
      this.options = { showCheckbox: false, allowEmpty: false }
      Object.extend(this.options, options || {});
      this._createForm();
}
Netvibes.DLA.SearchForm.prototype = {
  setFavicon: function(url, title) {
      this.favicon.src = url;
      if (typeof(title) != 'undefined') {
          this.favicon.alt = this.favicon.title = title;
      }
  },
  setSearchText: function(searchText) {
      this.inputSearch.value = searchText;
      this.resetButton.style.visibility = this.inputSearch.value.length? 'visible' : 'hidden'; 
      this.inputSearch.onblur();
  },
  setInitialState: function(favicon, searchText, checked) {
      this.setFavicon(favicon);
      this.inputSearch.value = searchText;
      this.resetButton.style.visibility = this.inputSearch.value.length? 'visible' : 'hidden';
      if (typeof checked != 'undefined' && this.checkbox) {
         this.checkbox.checked = checked;
      }
      this.inputSearch.onblur();
  },
  hide: function() {
      Element.hide(this.form);
  },
  show: function() {
      Element.show(this.form);
  },
  observe: function(name, observer) {
      if (!this.observers) this.observers = [];
      this.observers.push([name, observer]);
  },
  _notify: function(event) {
      if (!this.observers) return;
      var queryText = this.inputSearch.value;
      this.observers.each(function(observer) {
          if (observer[0] == event && typeof(observer[1]) == 'function') {
              observer[1](queryText.stripTags(), this.checkbox? this.checkbox.checked : null);
          }
      });
  },
  eventReset: function() {
      this._notify("reset");
      this.inputSearch.value = '';
      this.resetButton.style.visibility = "hidden";
      this.inputSearch.onblur();
      //Field.focus(this.inputSearch); // friendly?
      return false;
  },
  eventSubmit: function() {
      var queryText = this.inputSearch.value;
      if (queryText == "" && !this.options.allowEmpty) {
          return this.eventReset();
      }
      this._notify("submit");
      this.resetButton.style.visibility = "visible";
      return false;
  },
  eventToggle: function() {
      this._notify("toggle");
  },
  eventFocus: function() {
      this.submitButton.disabled = "";
      this._notify("focus");
  },
  eventBlur: function() {
  	/*if (this.inputSearch.value == "") {
  		this.resetButton.style.visibility = "hidden";
  		if (!this.options.allowEmpty) {
			this.submitButton.disabled = "disabled";
  		}
  	}*/
  	this._notify("blur");
  },
  _createForm: function() {
      this.container = document.createElement("div");
      this.container.className = 'search';
      this.form = document.createElement("form");
      this.form.style.display = 'block';
      if (!Browser.isIE) this.form.style.position = 'relative';

      this.form.onsubmit = this.eventSubmit.bindAsEventListener(this);
      this.favicon =  document.createElement("img");
      this.favicon.className = 'favicon';
      if (typeof this.options.faviconUrl != "undefined") {
          this.favicon.src = this.options.faviconUrl;
      }

      this.inputSearch = document.createElement("input");
      this.inputSearch.className = 'search';
      this.inputSearch.type = 'text';
      this.inputSearch.value = '';
      this.inputSearch.style.paddingRight = '18px';
      this.inputSearch.onfocus = this.eventFocus.bindAsEventListener(this);
      this.inputSearch.onblur = this.eventBlur.bindAsEventListener(this);

      this.resetButton = document.createElement("img");
      this.resetButton.title = this.resetButton.alt = _("Clear");
      this.resetButton.src = "http://" + NV_HOST + "/img/clear.gif";
      this.resetButton.className = "clear";
      //this.resetButton.style.cursor = 'pointer';
      //this.resetButton.style.marginLeft = '-21px';
      this.resetButton.style.marginTop = (Browser.isIE)? '-6px' : (Browser.isOpera)? '-2px' : (Browser.isSafari)? '-4px' : '-3px';
      this.resetButton.onclick = this.eventReset.bindAsEventListener(this);

      this.submitButton = document.createElement("input"); UWA.$element(this.submitButton);
	    this.submitButton.addClassName("submit");
      this.submitButton.type = 'submit';
      this.submitButton.value = _("Search");
      this.submitButton.style.marginLeft = '5px';

      this.container.appendChild(this.form);
      this.form.appendChild(this.favicon);
      this.form.appendChild(this.inputSearch);
      this.form.appendChild(this.resetButton);
      this.form.appendChild(this.submitButton);

      if (this.options.showCheckbox) {
          this.checkbox = document.createElement("input");
          this.checkbox.type = 'checkbox';
          this.checkbox.title = this.options.checkboxTitle;
          if (Browser.isIE) { // fixes bug with position: relative
              this.checkbox.style.marginLeft = "5px";
          } else {
              this.checkbox.style.position = 'absolute';
              this.checkbox.style.top = '5px';
              this.checkbox.style.right = '5px';
          }
          this.checkbox.value = '';
          this.checkbox.onclick = this.eventToggle.bindAsEventListener(this);
          this.form.appendChild(this.checkbox);
      }
  },
  appendTo: function(element) {
      element.appendChild(this.container);
  }
}

if (typeof UWA == "undefined") UWA = {};
if (typeof UWA.Controls == "undefined") UWA.Controls = {};
UWA.Controls.SearchForm = Netvibes.DLA.SearchForm;

/*
Copyright 2005-2007 Netvibes Ltd
All rights reserved.
Author : Jérémy Bethmont
*/

/*
Class: Netvibes.UI.FeedView

FeedView control is used into modules to display a Feed

Example:
    >var feedView = new Netvibes.UI.FeedView({ details: true, showDate: true });
    >
    >feedView.observe("onclick", MyModule.onClick);
    >feedView.observe("onmiddleclick", MyModule.onMiddleClick);
    >
    >feedView.addItem(0, item_0, 0;
    >feedView.addItem(1, item_1, 0);
    >feedView.addItem(2, item_2, 0);
    >feedView.addItem(3, item_3, 0);
*/

if (typeof Netvibes == "undefined" || !Netvibes) var Netvibes = {};

if (typeof Netvibes.UI == "undefined" || !Netvibes.UI) Netvibes.UI = {};

Netvibes.UI.FeedView = Class.create();

Netvibes.UI.FeedView.prototype = {

    setOptions: function(options) {
        this.options = { details: false,
                         openOutside: true,
                         showDate: true,
						 feedSiteUrlDomain: "", // for fixing relative URLs at thumbnails
                         lookForHtmlThumbnail: false,
						 removeImagePattern: false,
						 allowVideoPlayButton: false,
                         search: "",
                         dir: "ltr" };
        
        Object.extend(this.options, options || {});
    },
    
    initialize: function(options) {
        this._elements = [];
        this.setOptions(options);
        this._createList();
    },
    
    setSearch: function(search) {
        this.options.search = search;
    },
    
    resetSearch: function() {
        this.options.search = "";
    },
    
    addItem: function(index, item, status) {
        var li = document.createElement("li");
        var img = document.createElement("img");
        var a = document.createElement("a");

        var displayDesc = this._truncate(item.content.replace(/<\/?[^>]+>/gi, ' '), 100);
        if (this.options.search != "") {
            displayDesc = String.highlight(displayDesc, this.options.search);
        }

        a.href = item.link;
        a.target = "_blank";
        var displayTitle = item.title.stripTags();
        if (this.options.search != "") {
            displayTitle = String.highlight(displayTitle, this.options.search);
        }

        a.innerHTML = displayTitle;

        var diffDate = this._getDiffDate(item.date);
        if (diffDate) {
            var small = document.createElement("small");
            small.index = index;
            small.style.color = "#AAA";
            small.innerHTML = " - " + diffDate;
            a.appendChild(small);
        }
        
        if (!this.options.details) {
            a.desc = displayDesc;
            a.onmouseover = function() {
                UWA.Utils.setTooltip(this, this.desc, 250);
            }
        }
        a.index = index;

        a.onmouseup = this._onItemMouseDown.bindAsEventListener(this);
        a.onclick = this._onItemClicked.bindAsEventListener(this);

		var watchable = false;
		if (this.options.allowVideoPlayButton && item.video) {
			watchable = true;
		}

        if (item.enclosures && item.enclosures[0] && item.enclosures[0].url != '') {
            if (/^image\/(jpeg|gif|jpg|bmp|png)$/.test(item.enclosures[0].type)) {
                var thumbnail = item.enclosures[0].url;
            } else {
                var podcast = true;
                var mediaUrl = item.enclosures[0].url;
            }
            if (/^audio\/mpeg$/.test(item.enclosures[0].type) ||
                /\.mp3$/.test(item.enclosures[0].url)) {
                    var playable = true;
            }
        }

        if (this.options.lookForHtmlThumbnail) {
            // remove feedburner's "Email this" and other images
            // sometimes it's coming from the provider's domain, like: "feeds.cbsnews.com",
            // so we check the strange "/~r/" like path
            // and remove ads by matching /ads/ in the URL
            var cleanContent = item.content;
            cleanContent = cleanContent.replace(/src="http:\/\/[^"]+\/(~[rfa]|ads)\/[^"]+/mg, "");
            var matches = /<img.*?src=('|")?\s*(.*?)\s*('|"|\s*?\/?>|>)/i.exec(cleanContent);
            if (matches) {
				var thumbnail = matches[2].unescapeHTML();
			}
        }

        if (this.options.removeImagePattern && typeof thumbnail != "undefined") {
			if (thumbnail.match(new RegExp(this.options.removeImagePattern))) {
				thumbnail = '';
			}
		}

        if (typeof podcast != "undefined" && watchable != true) {
            a.style[this.options.dir == "rtl" ? "marginLeft" : "marginRight"] = "20px";
            var player = document.createElement("img");
            player.title = _("Play");
            player.style.border = "0px";
            player.style.cssFloat = this.options.dir == "rtl" ? "left" : "right";
    		player.style.styleFloat = this.options.dir == "rtl" ? "left" : "right";
    		if (typeof App != "undefined" && typeof playable != "undefined") {
                player.style.cursor = 'pointer';
        		player.fileLink = mediaUrl;
        		player.podName = displayTitle;
        		player.index = index;
        		player.src = "http://" + NV_HOST + "/img/speaker.gif";
        		player.onclick = this._onPodcastPlay.bindAsEventListener(this);
    	    } else {
    	        player.src = "http://" + NV_HOST + "/img/speaker-disabled.png";
    	    }

            var downloader = document.createElement("img");
    		downloader.title = _("Download");
            downloader.style.border = "0px";
    		downloader.style.cursor = 'pointer';
    		downloader.mediaUrl = mediaUrl;
    		downloader.index = index;
    		downloader.src = "http://" + NV_HOST + "/img/ipod.png";
    		downloader.style.cssFloat = this.options.dir == "rtl" ? "left" : "right";
    		downloader.style.styleFloat = this.options.dir == "rtl" ? "left" : "right";
    		downloader.style[this.options.dir == "rtl" ? "marginRight" : "marginLeft"] = "2px";
            downloader.onclick = this._onDownload.bindAsEventListener(this);
    		li.appendChild(downloader);
    		li.appendChild(player);
        }

		/*if (watchable == true) {
            a.style[this.options.dir == "rtl" ? "marginLeft" : "marginRight"] = "20px";

            var videoplayer = document.createElement("img");
            videoplayer.title = _("Play Video");
            videoplayer.style.border = "0px";
            videoplayer.style.cssFloat = this.options.dir == "rtl" ? "left" : "right";
    		videoplayer.style.styleFloat = this.options.dir == "rtl" ? "left" : "right";
    		if (typeof watchable != "undefined" && watchable) {
                videoplayer.style.cursor = 'pointer';
        		videoplayer.index = index;
        		videoplayer.src = "http://" + NV_HOST + "/img/speaker.gif";
        		videoplayer.onclick = this._onVideoPlay.bindAsEventListener(this);
    	    }

    		li.appendChild(videoplayer);
		}*/

        li.appendChild(a);

        if (this.options.details) {
            var descMargin = "0px";
            var h = document.createElement('h3');
            var p = document.createElement('p');
            if (item.thumbnail) {
                var thumbnail = item.thumbnail;
            }
            if (typeof thumbnail != "undefined" && thumbnail != '') {
				// we should trim the image url
				thumbnail = thumbnail.trim();
				// if the image's url is relative, we should fix it
				if (thumbnail.substring(0, 1) == "/" && this.options.feedSiteUrlDomain != '') {
					thumbnail = this.options.feedSiteUrlDomain + thumbnail;
				}
                var link = document.createElement("a");
                link.style.border = "0px";
                link.href = item.link;
                link.target = "_blank";
                link.index = index;
                link.style.outline = "none";
                link.onmouseup = this._onItemMouseDown.bindAsEventListener(this);
                link.onclick = this._onItemClicked.bindAsEventListener(this);
                var img = document.createElement("img");
                img.index = index;
                if (UWA.Client.Engine.ie) {
                    img.style.styleFloat = 'none';
                    img.style.textAlign = 'center';
                    img.onload = function() {
                        if (this.height >= 60 && this.width <= this.height) {
                            this.width = (60 * this.width) / this.height;
                            this.height = 60;
                            return ;
                        }
                        if (this.width >= 80 && this.width >= this.height) {
                            this.height = (80 * this.height) / this.width;
                            this.width = 80;
                            return ;
                        }
                    }
                } else if (UWA.Client.Engine.opera) {
					img.style.visibility = 'hidden';
                    img.style.styleFloat = 'none';
                    img.style.height = "60px";
					img.onload = function(){
						if (this.offsetWidth > 80) {
							this.style.height = Math.round(this.offsetHeight / this.offsetWidth * 80) + 'px';
							this.style.width = "80px";
						}
						this.style.visibility = '';
						/*
						if (this.offsetHeight >= 20 && this.offsetWidth >= 20) {
							this.style.visibility = '';
						} else {
                            li.removeChild(div);
                            p.style[this.options.dir == "rtl" ? "marginRight" : "marginLeft"] = "0px";
                            h.style[this.options.dir == "rtl" ? "marginRight" : "marginLeft"] = "0px";
						}
						*/
					}
                } else {
                    img.style.maxWidth = "80px";
                    img.style.maxHeight = "60px";
                    img.style.width = "inherit";
                    img.style.cssFloat = "inherit";
                }
                img.src = thumbnail;
                /*if (this.options.lookForHtmlThumbnail) {
                    img.onload = function() {
                        if (img.width < 20 || img.height < 10) {
                            li.removeChild(div);
                            p.style[this.options.dir == "rtl" ? "marginRight" : "marginLeft"] = "0px";
                            h.style[this.options.dir == "rtl" ? "marginRight" : "marginLeft"] = "0px";
                        }
                    }.bindAsEventListener(this);
                }*/
                
                var div = document.createElement("div");
                div.appendChild(link);
                div.style.width = "80px";
                div.style.height = "60px";
                div.style.textAlign = "center";
                div.style.cssFloat = this.options.dir == "rtl" ? "right" : "left";
                div.style.styleFloat = this.options.dir == "rtl" ? "right" : "left";
                li.appendChild(div);
                
                if (typeof watchable != "undefined" && watchable) {

                    var centerer = document.createElement("div");
                    centerer.style.width = "80px";
                    centerer.style.textAlign = "center";
                    centerer.style.cssFloat = centerer.style.styleFloat = "left";

                    var overlay = document.createElement("img");
                    overlay.src = "http://" + NV_HOST + "/img/play.png";
                    overlay.index = index;
                    overlay.onclick = this._onVideoPlay.bindAsEventListener(this);
                    overlay.style.marginLeft = "-80px";
                    overlay.style.cssFloat = overlay.style.styleFloat = "left";
                    overlay.style.width = "80px";
                    overlay.style.height = "60px";
                    if (UWA.Client.Engine.ie && UWA.Client.Engine.version == 6) {
                        overlay.src = "http://" + NV_HOST + "/img/s.gif";
                        overlay.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',src='http://"+NV_HOST+"/img/play.png');";
                    }
                    centerer.appendChild(img);
                    link.appendChild(centerer);
                    link.appendChild(overlay);
                    

                } else {
                    link.appendChild(img);
				}
                
                descMargin = "88px";
            }
            p.className = "description";
            p.style[this.options.dir == "rtl" ? "marginRight" : "marginLeft"] = descMargin;
            p.innerHTML = displayDesc;
            h.style[this.options.dir == "rtl" ? "marginRight" : "marginLeft"] = descMargin;
            h.appendChild(a);
            li.appendChild(h);
            var styleStatus = index % 2 ? "even" : "odd";
            li.className = "item " + styleStatus;
            li.style.backgroundImage = "none";
            li.appendChild(p);
                                
        }

        if (status == true) {
    	    li.className += " read";
    	} else {
    	    li.className += " unread";
    	}

    	this._elements[index] = li;

        if (!(this.options.search != "" && /* Search in Netvibes */
            this._searchInString(this.options.search, item.title) == false &&
            this._searchInString(this.options.search, item.content) == false)) {
                this._feedList.appendChild(li);
                this._numberDisplayedItems++;
        }
    },
    
    getContent: function() {
        return this._feedList;
    },
    
    getItem: function(index) {
        return this._elements[index];
    },
    
    getNumberOfDisplayedItems: function() {
        return this._numberDisplayedItems;
    },

    setRead: function(index) {
        var elem = this._elements[index];
        
        Element.addClassName(elem, "read");
        Element.removeClassName(elem, "unread");
    },
    
    setUnRead: function(index) {
        var elem = this._elements[index];
        
        Element.addClassName(elem, "unread");
        Element.removeClassName(elem, "read");
    },
    
    observe: function(name, observer) {
        if (!this.observers) this.observers = [];
        this.observers.push([name, observer]);
    },
    
    _notify: function(event, params) {
        if (!this.observers) return false;
        var ret = false;
        this.observers.each(function(observer) {
            if (observer[0] == event && typeof(observer[1]) == 'function') {
                ret = observer[1](params);
            }
        });
        return ret;
    },
    
    _createList: function() {
        this._numberDisplayedItems = 0;
        this._feedList = document.createElement("ul");
        if (this.options.details == true) {
            this._feedList.className = "nv-thumbnailedList";
            this._feedList.style.listStyleType = "none";
        } else {
            this._feedList.className = "nv-feedList";
        }
    },
        
    _searchInString: function(query, str) {
        var test = str.toLowerCase().indexOf(query.toLowerCase());
        if (test != -1) return true
        return false;
    },

    _onItemMouseDown: function(e) {
        if (typeof e == "undefined") e = event;
        
        var sender = (e.target || e.srcElement);
        
        // Middle click test - (Safari doesn't support middle click...)
        if ((typeof e.which == "undefined" && e.button == 4) || // Internet Explorer
            (e.which == 2 && e.button == 1) || // Gecko 1.0 or later and Opera 9
            (e.which == 2 && e.button == 4) || // Konqueror
            (e.which == 2 && e.button == 2) || // Gecko 0.9
            (e.which == 3 && e.button == 3) || // Opera 7
            (e.ctrlKey == true && !UWA.Client.Platform) || e.shiftKey == true) {
        	    this._notify("onmiddleclick", {index: sender.index});
        	    e.returnValue = true;
                return true;
    	}

        if (e.preventDefault)
        	e.preventDefault();
        else
        	e.returnValue = false;
        return false;
    },
    
    _onItemClicked: function(e) {
        if (typeof e == "undefined" && typeof event != "undefined") e = event;

        var sender = (e.target || e.srcElement);
        
        if (typeof e != "undefined" &&
            ((e.ctrlKey == true && !UWA.Client.Platform.mac) || e.shiftKey == true)) {
            return true;
        }

        return !this._notify("onclick", {index: sender.index});
    },
    
    _onPodcastPlay: function(e) {
        if (typeof e == "undefined") e = event;
        
        var sender = (e.target || e.srcElement);

        this._notify("onpodcastplay", {index: sender.index, fileLink: sender.fileLink, podName: sender.podName});
    },
    
    _onVideoPlay: function(e) {
        if (typeof e == "undefined") e = event;
        
        var sender = (e.target || e.srcElement);

        this._notify("onvideoplay", {index: sender.index});
    },
    
    _onDownload: function(e) {
        if (typeof e == "undefined") e = event;
        
        var sender = (e.target || e.srcElement);
        
        this._notify("ondownload", {index: sender.index, mediaUrl: sender.mediaUrl});
    },
    
    _getDiffDate: function(dateItem) {
        if (typeof dateItem == "undefined" ||
            !this.options.showDate) {
            return "";
        }

        var date = Date.parse(dateItem);
        
        if (isNaN(date)) { // The date is in ISO 8601 format?
            
            // 19/09/2007 +0800
            //if (dateItem.match(/[0-9]{2}\/[0-9]{2}\/[0-9]{4}\s[+-][0-9]{4}/)) {
            //}
            
            if (typeof Date.setISO8601 == "undefined") {
                Date.prototype.setISO8601 = function (string) {
                    var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
                        "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
                        "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
                        var d = string.match(new RegExp(regexp));
                        
                        var offset = 0;
                        var date = new Date(d[1], 0, 1);
                        
                        if (d[3]) { date.setMonth(d[3] - 1); }
                        if (d[5]) { date.setDate(d[5]); }
                        if (d[7]) { date.setHours(d[7]); }
                        if (d[8]) { date.setMinutes(d[8]); }
                        if (d[10]) { date.setSeconds(d[10]); }
                        if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
                        if (d[14]) {
                            offset = (Number(d[16]) * 60) + Number(d[17]);
                            offset *= ((d[15] == '-') ? 1 : -1);
                        }
                
                        offset -= date.getTimezoneOffset();
                        time = (Number(date) + (offset * 60 * 1000));
                        this.setTime(Number(time));
                }
            }
            
            date = new Date();
            date.setISO8601(dateItem);
            if (!date) return "";
        }
        
        var diff = new Date().getTime() - date;
        if (diff <= 0) return ""; // Time in the future...
        diff /= 1000;
        var time = {};
        time.sec = Math.floor(diff);
        time.min = Math.floor(diff / 60);
        time.hour = Math.floor(diff / 3600);
        time.day = Math.floor(diff / 86400);
        time.week = Math.floor(time.day / 7);
        time.month = Math.floor(time.day / 30);
        time.year = Math.floor(time.day / 365);

        var strTime;
        if (time.year == 1) {
            strTime = _("%s year ago").s(time.year);
        } else if (time.year > 1) {
            strTime = _("%s years ago").s(time.year);
        } else if (time.month == 1) {
            strTime = _("%s month ago").s(time.month);
        } else if (time.month > 1) {
            strTime = _("%s months ago").s(time.month);
        } else if (time.week == 1) {
            strTime = _("%s week ago").s(time.week);
        } else if (time.week > 1) {
            strTime = _("%s weeks ago").s(time.week);
        } else if (time.day == 1) {
            strTime = _("yesterday");
        } else if (time.day > 1) {
            strTime = _("%s days ago").s(time.day);
        } else if (time.hour == 1) {
            strTime = _("%s hour ago").s(time.hour);
        } else if (time.hour > 1) {
            strTime = _("%s hours ago").s(time.hour);
        } else if (time.min == 1) {
            strTime = _("%s minute ago").s(time.min);
        } else if (time.min > 1) {
            strTime = _("%s minutes ago").s(time.min);
        } else if (time.sec == 1) {
            strTime = _("%s second ago").s(time.sec);
        } else if (time.sec > 1) {
            strTime = _("%s seconds ago").s(time.sec);
        }
        
        return strTime;
    },
    
    _truncate: function(s, size) {
        if (!size) size = 30;
    	if (s.length <= size) return s;

    	var punctuation = '.,;!? ';
    	p = -1;
    	for (var i = 0; i < size; i++) {
    		if (punctuation.indexOf(s.charAt(i)) != -1) {
    			p = i;
    		}
    	}
    	if (p == -1) p = size - 1;
    	return '' + s.substr(0, p) + '...';
    }

}

var Cookie = new Object();

Cookie.get = function(name) {
	var start = document.cookie.indexOf(name + "=");
	var len = start + name.length + 1;
	if ((!start) && (name != document.cookie.substring(0, name.length))) {
		return null;
	}
	if (start == -1) return null;
	var end = document.cookie.indexOf(";", len);
	if (end == -1) end = document.cookie.length;
	return unescape(document.cookie.substring(len, end));
};

Cookie.set = function(name, value) {
	var today = new Date();
	today.setTime(today.getTime());
	var expires_date = new Date(today.getTime() + 31536000000);
	document.cookie = name + "=" + escape(value) + ";expires=" + expires_date.toGMTString();
};

Cookie.remove = function(name) {
	if (getCookie(name)) document.cookie = name + "=;expires=Thu, 01-Jan-1970 00:00:01 GMT";
};

/*
Script: UWA.js

Copyright 2005-2007 Netvibes Ltd.
All rights reserved.
*/

/* NV Globals */

if(typeof window.NV_HOST == "undefined") {
  NV_HOST = 'www.netvibes.com';
}
if(typeof window.NV_STATIC == "undefined") {
  NV_STATIC = 'http://' + NV_HOST;
}
if(typeof window.NV_PATH == "undefined") {
  NV_PATH = '/';
}

if (typeof UWA == "undefined") var UWA = Uwa /* alias */ = {};

UWA.version = '1.0';

UWA.require = function(library) {
  // following line needed, cause buggy library list definition
  if(typeof library == "object") { for(var i in library) { UWA.require(library[i]) } return }
  if (library.indexOf("http://") == -1) library = UWA.path + library;
  var script = document.createElement('script');
  script.setAttribute('type', 'text/javascript');
  script.src = library;
  var head = document.getElementsByTagName('head')[0];
  head.appendChild(script);
}

UWA.load = function() {
  var scripts = document.getElementsByTagName("script");
  for (var i = 0, j = scripts.length; i < j; i++) {
    var script = scripts[i];
    var regexp = /UWA\.js(\?.*)?$/;
    if (script.src && script.src.match(regexp)) {

      // Extracts base path
      UWA.path = script.src.replace(regexp, '');

      // Extracts env
      var matchEnv = script.src.match(/\?.*env=([a-zA-Z,_]*)/);
      if (matchEnv && matchEnv[1]) {
        UWA.env = matchEnv[1];
      }
    }
  }

  // Required scripts
  if (UWA.env && UWA.Libs[UWA.env]) {
    var files = UWA.Libs[UWA.env];
    for (var i = 0, j = files.length; i < j; i++) {
       UWA.require(files[i]);
    }
  }
}

// Library & Dependances definitions

UWA.Libs = {};

UWA.Libs.Core = [];
UWA.Libs.Core.push('Core/Core.js', 'Core/String.js', 'Core/Array.js', 'Core/Json.js', 'Core/Client.js' );

// Auto-detects contextual javascript framework
if (window.Prototype != undefined) {
    UWA.Libs.Core.push('Drivers/UWA-prototype.js');

} else if (window.MooTools != undefined) {
    // UWA.Libs.Core.push('../moocompat.js');
    UWA.Libs.Core.push('Drivers/UWA-mootools.js');

} else if (window.jQuery != undefined) {
    UWA.Libs.Core.push('Drivers/UWA-jquery.js');

} else if (window.YAHOO != undefined) {
    UWA.Libs.Core.push('Drivers/UWA-yahoo.js');
          
} else {
    UWA.Libs.Core.push('../mootools.js');
    UWA.Libs.Core.push('../moocompat.js');
    UWA.Libs.Core.push('Drivers/UWA-mootools.js');
}

UWA.Libs.Core.push('Widget.js', 'Environment.js', 'Data.js', 'Element.js', 'Utils.js');

UWA.Libs.Standalone = [];
UWA.Libs.Standalone.push(UWA.Libs.Core);
UWA.Libs.Standalone.push('Utils/Cookie.js', 'Environments/Standalone.js', 'Controls/PrefsForm.js');

UWA.Libs.Frame_UWA_Netvibes = [];
UWA.Libs.Frame_UWA_Netvibes.push(UWA.Libs.Core);
UWA.Libs.Frame_UWA_Netvibes.push('Environments/Frame.js', 'Environments/Frame_UWA_Netvibes.js');

UWA.Libs.Frame_Google = [];
UWA.Libs.Frame_Google.push(UWA.Libs.Core);
UWA.Libs.Frame_Google.push('Environments/Frame.js', 'Environments/Frame_Google.js');


// Load UWA

UWA.load();


// Compatibility

if (typeof Netvibes == "undefined") var Netvibes = {};
if (typeof Netvibes.UI == "undefined") Netvibes.UI = {};
Netvibes.UI._idIncrement = 0;
if (typeof UWA.Controls == "undefined") UWA.Controls = {};
UWA.Controls = Netvibes.UI;
if (Netvibes.DLA) UWA.Controls.SearchForm = Netvibes.DLA.SearchForm;

/*
Script: Core.js

Copyright 2005-2007 Netvibes Ltd.
All rights reserved.

*/

if (typeof UWA == "undefined") var UWA = {};

UWA.extend = function() {
    for (var property in arguments[1]) arguments[0][property] = arguments[1][property];
    return arguments[0];
}

UWA.merge = function() {
    for (var property in arguments[1]) {
      if(typeof arguments[0][property] == "undefined")
        arguments[0][property] = arguments[1][property];
    }
    return arguments[0];
}

UWA.log = function(string) {
    if (window.console) console.log(string); // firebug, safari
    else if (window.opera) opera.postError(string);
    // else if (window.widget) window.alert(string); // dashboard
    // else window.alert(string); // IE
}

/*
Script: Json.js

Copyright 2005-2007 Netvibes Ltd.
All rights reserved.

Credits:
    Partially based on MooTools Framework - copyright (c) 2007 Valerio Proietti, <http://mad4milk.net>
*/

if (typeof UWA == "undefined") var UWA = {};

if (typeof UWA.Json == "undefined") UWA.Json = {};

/*
Class: Json
    Json parser and Stringyfier, See: <http://www.json.org/>
*/

UWA.extend(UWA.Json, {
  
  getType: function(obj){
  	if (obj == undefined) return false;
  	if (obj.htmlElement) return 'element';
  	var type = typeof obj;
  	if (type == 'object' && obj.nodeName){
  		switch(obj.nodeType){
  			case 1: return 'element';
  			case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
  		}
  	}
  	if (type == 'object' || type == 'function'){
  		switch(obj.constructor){
  			case Array: return 'array';
  			case RegExp: return 'regexp';
  			case Class: return 'class';
  		}
  		if (typeof obj.length == 'number'){
  			if (obj.item) return 'collection';
  			if (obj.callee) return 'arguments';
  		}
  	}
  	return type;
  },
  
  encode: function(obj){
		switch( UWA.Json.getType(obj) ){
			case 'string':
				return '"' + obj.replace(/(["\\])/g, '\\$1') + '"';
			case 'array':
				return '[' + obj.map(UWA.Json.encode).join(',') + ']';
			case 'object':
				var string = [];
				for (var property in obj) string.push(UWA.Json.encode(property) + ':' + UWA.Json.encode(obj[property]));
				return '{' + string.join(',') + '}';
			case 'number':
				if (isFinite(obj)) break;
			case false:
				return 'null';
		}
		return String(obj);
	},

  decode: function(str){
    var regex = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;
    if (typeof str == 'string' && regex.test(str)) {
      return eval('(' + str + ')');
    }
    return null;
  }

});

/*
Script: Array.js

Copyright 2005-2007 Netvibes Ltd.
All rights reserved.

Credits:
    Partially based on MooTools Framework - copyright (c) 2007 Valerio Proietti, <http://mad4milk.net>
*/

// Standard Javascript 1.6 methods

UWA.merge(Array.prototype, {

	forEach: function(fn, bind){
		for (var i = 0, j = this.length; i < j; i++) fn.call(bind, this[i], i, this);
	},

	filter: function(fn, bind){
		var results = [];
		for (var i = 0, j = this.length; i < j; i++){
			if (fn.call(bind, this[i], i, this)) results.push(this[i]);
		}
		return results;
	},

	map: function(fn, bind){
		var results = [];
		for (var i = 0, j = this.length; i < j; i++) results[i] = fn.call(bind, this[i], i, this);
		return results;
	},

	every: function(fn, bind){
		for (var i = 0, j = this.length; i < j; i++){
			if (!fn.call(bind, this[i], i, this)) return false;
		}
		return true;
	},

	some: function(fn, bind){
		for (var i = 0, j = this.length; i < j; i++){
			if (fn.call(bind, this[i], i, this)) return true;
		}
		return false;
	},

	indexOf: function(item, from){
		var len = this.length;
		for (var i = (from < 0) ? Math.max(0, len + from) : from || 0; i < len; i++){
			if (this[i] === item) return i;
		}
		return -1;
	}

});

// Deprecated and obsolete - backward compatibility with competitor UWA implementation

Array.prototype.normalize = function(sum) {
    var x = 0;
    var ratio = sum / this.inject(0, function(a, n) { return a + n; } );
    for (var i = 0; i < this.length - 1; i++) x += (this[i] *= ratio);
    this[this.length - 1] = sum - x;
}

Array.prototype.equals = function(compare) {
  if (!compare) {
    return false;
  }
  var len = this.length;
  if (len != compare.length) {
    return false;
  }
  for (var i = 0; i < len; i++) {
    if (this[i] != compare[i]) {
      return false;
    }
  }
  return true;
}

/*
Script: String.js

Copyright 2005-2007 Netvibes Ltd.
All rights reserved.

Credits:
    Partially based on Prototype Framework - (c) 2005-2007 Sam Stephenson
*/

UWA.merge(String.prototype, {
  
  trim: function(){
		return this.replace(/^\s+/, '').replace(/\s+$/, '');
	},
	
	isEmail: function() {
      var regexp = /^([a-zA-Z0-9_.\-+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
      return regexp.test(this);
  },
	
  stripTags: function() {
		return this.replace(/<\/?[^>]+>/gi, '');
	},
	
	truncate: function(length, truncation) {
      length = length || 30;
      truncation = truncation === undefined ? '...' : truncation;
      return this.length > length ?
          this.slice(0, length - truncation.length) + truncation : this;
  },
  
  s: function() {
    var str = this;
    if (arguments.length < 1) return str;
    var re = /([^%]*)%s(.*)/;
    var a = [], numSubstitutions = -1;
    while (a = re.exec(str)) {
        var leftpart = a[1], rightPart = a[2];
        if (++numSubstitutions >= arguments.length) {
            break;
        }
        str = leftpart + arguments[numSubstitutions] + rightPart;
    }
    return str;
  },
  
  escapeRE: function() {
    return this.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
  }
	
});

/*
Script: Client.js

Credits:
    Partially based on MooTools Framework - copyright (c) 2007 Valerio Proietti, <http://mad4milk.net>
    
Class: Client
	Some browser properties are attached to the Client object for browser detection.

Engine:
	UWA.Client.Engine.ie - is set to true if the current browser is internet explorer (any)
	UWA.Client.Engine.ie6 - is set to true if the current browser is internet explorer 6
	UWA.Client.Engine.ie7 - is set to true if the current browser is internet explorer 7
	UWA.Client.Engine.gecko - is set to true if the current browser is Mozilla/Gecko
	UWA.Client.Engine.webkit - is set to true if the current browser is Safari/Konqueror
	UWA.Client.Engine.webkit419 - is set to true if the current browser is Safari2 / webkit till version 419
	UWA.Client.Engine.webkit420 - is set to true if the current browser is Safari3 (Webkit SVN Build) / webkit over version 419
	UWA.Client.Engine.opera - is set to true if the current browser is opera
	UWA.Client.Engine.name - is set to the name of the engine

Platform:
	UWA.Client.Platform.mac - is set to true if the platform is mac
	UWA.Client.Platform.windows - is set to true if the platform is windows
	UWA.Client.Platform.linux - is set to true if the platform is linux
	UWA.Client.Platform.other - is set to true if the platform is neither mac, windows or linux
	UWA.Client.Platform.name - is set to the name of the platform

Note:
	Engine detection is entirely object-based.
*/

if (typeof UWA == "undefined") var UWA = {};

UWA.Client = {Engine: {'name': 'unknown', 'version': ''}, Platform: {}, 'features': {}};

//features
UWA.Client.features.xhr = !!(window.XMLHttpRequest);
UWA.Client.features.xpath = !!(document.evaluate);

//engine
if (window.opera) UWA.Client.Engine.name = 'opera';
else if (window.ActiveXObject) UWA.Client.Engine = {'name': 'ie', 'version': (UWA.Client.features.xhr) ? 7 : 6};
else if (!navigator.taintEnabled) UWA.Client.Engine = {'name': 'webkit', 'version': (UWA.Client.features.xpath) ? 420 : 419};
else if (document.getBoxObjectFor != null) UWA.Client.Engine.name = 'gecko';
UWA.Client.Engine[UWA.Client.Engine.name] = UWA.Client.Engine[UWA.Client.Engine.name + UWA.Client.Engine.version] = true;

//platform
var platform = navigator.platform.match(/(mac)|(win)|(linux)|(nix)/i) || ['Other'];
UWA.Client.Platform.name = platform[0].toLowerCase();
UWA.Client.Platform[UWA.Client.Platform.name] = true;

// Retro compatibility with old Browser object
if (typeof Browser == "undefined") var Browser = {};
if(UWA.Client.Engine.ie) Browser.isIE = true; else Browser.isIE = false;
if(UWA.Client.Engine.opera) Browser.isOpera = true; else Browser.isOpera = false;

if (typeof UWA == "undefined") var UWA = {};

UWA.Class = Class;

UWA.Form = {
  getElements: function(form) {
    
    // commented code is bugged with IE7 (mootools issue)
    // return form.getElementsBySelector('input, textarea, select');
    
    var search = [];
    search.push( form.getElementsByTagName('input') );
    search.push( form.getElementsByTagName('textarea') );
    search.push( form.getElementsByTagName('select') );
    
    var results = [];
    for(var i = 0; i < search.length; i++) {
      for(var j = 0; j < search[i].length; j++) {
        results.push( search[i][j] );
      }
    }
    return results;
    
  }
}

UWA.Ajax = {
  Request: function(url, request) {
    if(request.method) request.method = request.method.toLowerCase();
    if(request.parameters) request.data = request.parameters;
    // if(request.postBody) request.data = request.postBody;
    if(request.requestHeaders) request.headers = request.requestHeaders;
    return new Ajax(url, request).request();
  },
  onCompleteXML: function(arg, callback, context) {
    if(typeof callback == "function") callback(arg[1])
  },
  onCompleteText: function(arg, callback, context) {
    if(typeof callback == "function") callback(arg[0])
  },
  onCompleteFeed: function(arg, callback, context) {
    var response = {responseText: arg[0], responseXML: arg[1]};
    var feed = UWA.Utils.parseFeed(response);
    if(typeof callback == "function") callback(feed)
  },
  onCompleteJson: function(arg, callback, context) {
    try {
      eval("var j = " + arg[0]);
      if(typeof callback == "function") callback(j, context);
    } catch(e) {
      UWA.log(e);
    }
  }
}

UWA.$element = function(el){
  if (el) {
    if (!el.isUwaExtended) {
      UWA.extend(el, UWA.Element);
      el.isUwaExtended = true;
    }
    return $(el);
  }
}

if (typeof UWA.Element == "undefined") UWA.Element = {};

// if (typeof UWA.Element.methods == "undefined") UWA.Element.methods = {};

UWA.extend(UWA.Element, {
  
  hasClassName: function(className) {
    return this.hasClass(className);
  },
  addClassName: function(className) {
    return this.addClass(className);
  },
  removeClassName: function(className) {
    return this.removeClass(className);
  },
  hide: function() {
   return this.setStyle('display', 'none');
  },
  show: function() {
    return this.setStyle('display', '');
  },
  toggle: function() {
    if(this.style.display == 'none') {
      this.style.display = '';
    } else {
      this.style.display = 'none';
    }
  },
  getDimensions: function() {
    // return Element.getDimensions(this); // from moocompat - to be integrated into UWA core
    var dimensions = this.getSize();
    return { 'width' : dimensions.size.x , 'height' : dimensions.size.y }
  }
  
} );

/*
Script: Element.js

Copyright 2005-2007 Netvibes Ltd.
All rights reserved.
*/

if (typeof UWA == "undefined") var UWA = {};
if (typeof UWA.Element == "undefined") UWA.Element = {};
// if (typeof UWA.Element.methods == "undefined") UWA.Element.methods = {};

UWA.extend(UWA.Element, {

  addContent: function(content) {
    if (typeof content == 'string') {
      var node = document.createElement("div");
      node.innerHTML = content;
      return this.appendChild(node);
    }
    return this.appendChild(content);
  },

  appendText: function(text) {
    var node = document.createTextNode(text);
    return this.appendChild(node);
  },

  setText: function(text) {
    this[(typeof this.innerText != 'undefined') ? 'innerText' : 'textContent'] = text;
    return this;
  },

  setHTML: function(html) {
    this.innerHTML = html;
    return this;
  },

  setContent: function(content) {
    if (typeof content == 'string') {
      this.setHTML(content);
    } else if (typeof content == 'object') {
      this.empty();
      this.appendChild(content);
    }
    return this;
  },

  empty: function() {
    this.innerHTML = '';
    return this;
  },
  
  getParent: function(){
		return this.parentNode;
	},

	getChildren: function(){
		return this.childNodes;
	}

});

/* Class: UWA.Widget

The Module class provides abstract methods to create and manipulate Netvibes modules.
Once created, it must be registered into an execution environnement to be runned.

_Copyright 2006-2007 Netvibes. All rights reserved._

Example:
Usually, the easiest way to create a Module is to get it from the Environment
(start code)
...
var aModule = Environment.getModule();
...
(end)

*/

if (typeof UWA == "undefined") var UWA = {};

UWA.Widget = function() {
    
    /* Property: id 

    *String*: Unique identifier of the module.
    
    The value depends on the execution environment: the Environment registration handler sets this property.
    */
    this.id = '';

    /* Property: environment

    *Object*: Reference to the execution environnement.
    
    The Environment registration handler sets this property.
    */
    this.environment = null;

    /* Property: data
  
    *Collection{Object}*: Stores module's data (defined in the skeleton properties).
    
    This property can be modified by the "<setValue>" method, and accessed by the "<getValue>" method.
    */
    this.data = {};

    /* Property: callbacks
    
    *Collection{Object}*: Module's callback methods.
    
    The collection is initially empty. Callback methods are added by the "<setCallback>" method, and are launched by the "<callback>" method.
    */
    this.callbacks = {};

    /* Property: preferences
    
    *Array[Object]*: Stores module's preferences. 
    
    The array is initially empty. It is initialised by the "<setPreferences>" method.
    */
    this.preferences = [];
    
    /* to document */
    this.periodicals = {};
    
    /* Property: searchResultCount
    
    *Integer*: the search result count when the module is onSearch.
    
    This property is set by the "<setSearchResultCount>" method.
    */
    this.searchResultCount = 0;
    
    /* Property: unreadCount
    
    *Integer*: the count of unread items in the module.
    
    The unread count is set by the "<setUnreadCount>" method.
    */
    this.unreadCount = 0;
    
    /* Property: prefsForm
    
    *Object*: the preference's form of the module.
    
    */
    /* deprecated */
    this.prefsForm = null;
    
    /* Property: title
    
    *String*: module's title.
    
    The title of the module. It is set by the "<setTitle>" method.
    */
    this.title = '';
    
    /* Property: debugMode
    
    *Boolean*: activates or desactivates the debug mode for the module. 
    
    The default value is TRUE. When TRUE, messages written with "widget.log" will appear in the console.
    */
    this.debugMode = false;
    
    /* to document */
    this.elements = {};
    
    /* to document */
    this.metas = {};
    
    /* deprecated */
    this.inline = false;
    
    /* to document */
    this.apiVersion = '1.0';
    
    /* to document */
    this.lang = 'en_US';
    
    /* to document */
    this.locale = 'us';
    
    /* to document */
    this.dir = 'ltr';
    
    if(this.initialize) this.initialize();

}

UWA.Widget.prototype = {
  
  /* Method: setTitle
  
  Sets the title of the Module.
  
  Parameters:
  * String - title: The title of the module. 
  
  Returns:
  * Nothing, but calls the method associated with the "onUpdateTitle" callback. 
  The callback method is set with the "<setCallback>" method.
  
  Example:
  In the HTML skeleton of the module:
  (start code)
  ...
  widget.debugMode = true;
  ...
  var myUpdateTitle = function () {
    widget.log("onUpdateTitle was called");
  }
  ...
  widget.setCallback("onUpdateTitle", myUpdateTitle);
  ...
  widget.setTitle('New title');
  ...
  (end)
  The console should display "onUpdateTitle was called" after the "setTitle" method was called.
  */
  setTitle: function(title, extended) {
    this.title = title;
    if (this.elements['title']) {
      if (extended) {
         extended = ' ' + extended + '';
       } else {
         extended = '';
       }
      this.elements['title'].setHTML(title + extended);
    }
    if (this.environment && this.environment.setTitle) this.environment.setTitle(title);
  },
  
  /* to document */
  getTitle: function() {
    if (this.environment && this.environment.getTitle) return this.environment.getTitle();
    return this.title.stripTags(); // stripTags = prototype.js
  },
  
  /* Method: setBody
  
  Sets the body of the Module. Erases the previous body.
  
  Parameters:
  * Object - content: The body of the module.
  
  Returns:
  * Nothing, but calls the methods associated with the "onUpdateBody" callback. 
  For backward compatibility, it also calls the method associated with the *DEPRECATED* "onUpdateContent" callback.
  Those methods must be defined in the HTML skeleton of the Module.
  Callback methods are set with the "<setCallBack>" method.
  
  Example: 
  See the exemple of <setTitle> for callback assignation
  */
  setBody: function(content) {
    this.body.setContent(content);
    this.callback('onUpdateBody');
  },
  
  /* Method: addBody
  
  Adds contents to the existing body of the Module.
  
  Parameters:
  * Object - content: The content to add in the body of the module.
  
  Returns:
  * Nothing, but calls the methods associated with the "onUpdateBody" callback. 
  This method must be defined in the HTML skeleton of the Module.
  Callback methods are set with the "<setCallBack>" method.
  
  Example: 
  See the exemple of <setTitle> for callback assignation
  */
  addBody: function(content) {
    this.body.addContent(content);
    this.callback('onUpdateBody');
  },

  /* Method: setIcon
  
  Sets the icon for the Module.
  
  Parameters:
  * String - URL: the URL pointing to the ICON. The URL must include the protocol (http://)
  
  Returns:
  * Nothing.
  
  Examples:
  (start code)
  ...
  this.setIcon("http://www.netvibes.com/favicon.ico");
  ...
  (end)
  */
  setIcon: function(url) {
    if (this.environment.setIcon) this.environment.setIcon(url);
    else if(this.elements['icon']) this.elements['icon'].setHTML('<img width="16" height="16" src="' + url + '" />');
  },
  
  /* deprecated */
  setElementId: function(element, id) {
    this.log('widget.setElementId is deprecated');
    this.$(element).setAttribute('id', 'm_' + this.id + '_' + id);
  },

  /* Method: createElement
  
  Creates a new element according to the provided "tagName".
  
  Parameters:
  * String - tagName: the HTML tag name of the element to create.
  
  Returns:
  * Element: The created element.
  
  Example:
  (start code)
  ...
  aDiv = this.createElement('div');
  ...
  (end)
  aDiv is now the Element object for an HTML DIV tag.
  */
  createElement: function(tagName, elName) {
    if (tagName == 'script' ) return false; // blacklist here
    var el = document.createElement(tagName);
    if (typeof elName == 'string') {
      this.elements[elName] = el;
    } 
    return UWA.$element(el);
  },

  /* deprecated */
  $: function(el) {
    this.log('widget.$ is deprecated');
    if (typeof el == 'string' && this.elements[el]) {
      el = this.elements[el];
    }
    return UWA.$element(el);
  },

  /* Method: initPreferences
  
  Initializes preferences of the module. The method gets values from the environnement.
  We values do not exist in the environment, it sets them to their default values.
  
  This method is called by the "<launch>" method of the Module, and when the module is registered in the Environment.
  
  Parameters:
  * None.
  
  Returns:
  * Nothing.
  */
  initPreferences: function() {
    for(var i = 0; i < this.preferences.length; i++) {
      var pref = this.preferences[i];
      if (typeof pref.name == "undefined") continue; // no name = preference ignored
      if (pref.defaultvalue) pref.defaultValue = pref.defaultvalue; // fix after xml parsing
      var value = this.getValue(pref.name);
      if (value == undefined || value == null || value == 'undefined') { // the last not really needed but could help
        if (typeof pref.defaultValue != "undefined") this.data[pref.name] = pref.defaultValue;
        else this.data[pref.name] = null;
      }
      if(pref.defaultValue && value && pref.defaultValue == value) {
        if (this.environment && this.environment.deleteData) this.environment.deleteData(pref.name);
      }
    }
  },
  
  /* to document */
  getPreference: function(name) {
    for(var i = 0; i < this.preferences.length; i++) {
      if(this.preferences[i].name == name) return this.preferences[i];
    }
    return null;
  },
  
  /* Method: setPreferences
  
  Sets preferences of the module. Replaces previous preferences.
  
  Parameters:
  * Array[Collection{String}] - schema: the set of preferences, as an array, for the module.

  Returns:
  * Nothing.
  */
  setPreferences: function(schema) {
    this.preferences = schema;
  },
  
  /* Method: addPreference
  
  Adds a single preferences to the existing preferences of the module.
  
  Parameters:
  * Collection{String} - preference: the set of preferences, as a collection, for the module. 
  A preference is a collection of Strings, with one entry. 
  The key is the name of the preference, and the value is the value of the preference.

  Returns:
  * Nothing.
  
  Example:
  (start code)
  ...
  aPreference = {};
  aPreference['name'] = "offset";
  widget.addPreference(aPreference);
  ...
  (end)
  */
  addPreference: function(preference) {
    this.preferences.push(preference);
  },
  
  /* to document */
  setPreferencesXML: function(prefs) {
    this.setPreferences( [] ); // empty preferences array
    for(var i = 0; i < prefs.length; i++) {
      var preference = {};
      for(var j = 0; j < prefs[i].attributes.length; j++) {
        var name = prefs[i].attributes[j]['nodeName'];
        var value = prefs[i].attributes[j]['nodeValue'];
        preference[name] = value;
      }
      if (preference.type == 'list') {
        var options = prefs[i].getElementsByTagName("option");
        preference.options = [];
        for(var j = 0; j < options.length; j++) {
          var option = {};
          if ( options[j].attributes[0]['value'] ) option[options[j].attributes[0]['name']] = options[j].attributes[0]['value'];
          if ( options[j].attributes[1]['value'] ) option[options[j].attributes[1]['name']] = options[j].attributes[1]['value'];
          preference.options.push(option)
        }
      }
      this.addPreference(preference);
    }
  },
  
  /* to document */
  setMetasXML: function(metas) {
    var metasArray = [];
    for(var i = 0; i < metas.length; i++) {
      if(metas[i].name) var name = metas[i].name;
      else var name = metas[i].attributes[0]['nodeValue'];
      if(metas[i].content) var value = metas[i].content;
      else var value = metas[i].attributes[1]['nodeValue'];
      if(value == 'false') value = false; else if(value == 'true') value = true; // booleanise
      metasArray[name] = value;
    }
    this.setMetas(metasArray);
  },
  
  /* to document */
  setMetas: function(metas) {
    this.metas = metas;
    if(this.metas.debugMode) this.setDebugMode(this.metas.debugMode);
    if(this.metas.autoRefresh) this.setAutoRefresh(this.metas.autoRefresh);
  },
  
  /* Method: getValue
  
  Gets the value of the given preference of the module.
  *Todo*: maybe we can force the type against preferences?
  
  Parameters:
  * String - name: the name of the preference we want the value of.
  
  Returns:
  * Nothing.
  */
  getValue: function(name) {
    if (this.data[name] != undefined) return this.data[name];
    if(this.environment && this.environment.getData) {
      var value = this.environment.getData(name);
      if (value == 'null') value = null;
      this.data[name] = value;
      return value;
    }
    return null;
  },
  
  /* to document */
  getInt: function(name) {
    var value = this.getValue(name);
    if(value == 'true' || value == true) value = 1;
    value = parseInt(value, 10);
    return isNaN(value) ? 0 : value;
  },
  
  /* to document */
  getBool: function(name) {
    return this.getInt(name) ? true : false;
  },
  
  /* Method: setValue
  
  Sets the value of the given preference of the module. 
  It sets the value internally first, and then calls the Environnement dedicated function.
  
  Parameters:
  * String - name: the name of the preference we want to set.
  * Object - value: the value of the preference (String, Integer, etc.)
  
  Returns:
  * Object: the value of the preference we set.
  */
  setValue: function(name, value) {
    this.data[name] = value;
    var pref = this.getPreference(name);
    // if(pref && pref.defaultValue && pref.defaultValue == value) {
    // if (this.environment && this.environment.deleteData) this.environment.deleteData(name);
    // } else {
      if (this.environment && this.environment.setData) this.environment.setData(name, value);
    // }
    return value;
  },
  
  /* to document */
  saveValues: function(callback) {
    if (this.environment && this.environment.saveDatas) {
      this.environment.saveDatas(callback);
    } else {
      callback();
    }
  },

  /* Method: setAutoRefresh
  
  Sets the auto-refresh interval for the module. 
  The module must define a "onRefresh" method for the auto-refresh to work properly.
  
  Parameters:
  * Integer - delay: the refresh delay, in *milliseconds*.
  
  Returns:
  * Nothing.
  
  Example:
  (start code)
  ...
  widget.setAutoRefresh(20); // Set the auto-refresh interval to 20 minutes
  ...
  (end)
  */
  setAutoRefresh: function(delay) {
    var rndUpdateTime = Math.round(10*1000*Math.random());
    if (this.onRefresh) {
      delay = parseInt(delay) * 1000 * 60; // from minutes to milliseconds
      this.setPeriodical('autoRefresh', this.onRefresh, delay + rndUpdateTime);
    }
  },
  
  /* to document */
  setPeriodical: function(name, fn, delay, force) {
    this.clearPeriodical(name);
    this.periodicals[name] = setInterval(fn.bind(this), delay);
    if (force) fn();
  },
  
  /* to document */
  clearPeriodical: function(name) {
    if (this.periodicals[name]) { clearInterval(this.periodicals[name]) }
  },

  /* Method: setCallback
  
  Associates a function to a callback key.
  
  Parameters:
  * String - name: the name of the callback (e.g. "onUpdateTitle"),
  * Function - fn: the function to call when the callback key is used.

  Returns:
  *Nothing.
  
  Example:
  See the example of the "<setTitle>" method.
  */
  setCallback: function(name, fn) {
    this.callbacks[name] = fn;
  },
  
  /* Method: callback
  
  Executes the callback method associated with the given callback name (key). 
  Returns false if no callback method is associated with the given key.
  
  *Notes*: would be good to allow more parameters through apply() style function
  
  Parameters:
  * String - name: the callback name (e.g. "onUpdateTitle");
  * Object
  
  Returns:
  * Nothing, but calls the method associated with the given callback name (key) 
  * *OR* a Boolean set to False, if no method is found for the given callback name.
  */
  callback: function(name, args, bind) {
    if (typeof bind == 'undefined') bind = this;
    try {
      if (this[name]) this[name].apply(bind, [args]);
      if (this.callbacks[name]) this.callbacks[name].apply(bind, [args]);
    } catch(e) {
      UWA.log(e);
    }
    if(this.environment && this.environment.callback) this.environment.callback(name); 
  },
  
  /* Method: setSearchResultCount
  
  Sets the search result count.
  
  Parameters:
  * Integer - count: the count of results for the current search terms.
  
  Returns:
  * Nothing, but updates the title with the result count, if greater or equal to zero.
  */
  setSearchResultCount: function(count) {
    this.searchResultCount = count;
    if (this.environment.setSearchResultCount) this.environment.setSearchResultCount(count);
    if (count > 0) this.setTitle(this.title, '<span class="result">(' + count + ')</span>');
    else if (count === 0) this.setTitle(this.title, '<span class="result">(' + _("no results") + ')</span>');
    else this.setTitle(this.title);
  },

  /* Method: setUnreadCount 
  
  Sets the count of unread items.
  
  Parameters:
  * Integer - count: the count of unread items.
  
  Returns:
  * Nothing, but updates the title with the unread count, if greater or equal to zero.
  */  
  setUnreadCount: function(count) {
    this.unreadCount = count;
    if (this.environment && this.environment.setUnreadCount) this.environment.setUnreadCount(count);
  },

  /* Method: launch
  
  Launches the module. In principle, this method is not called directly. 
  It is called by the Environment, as it sets a number of other necessary requirements to launch the module.
  
  Parameters:
  * None.
  
  Returns:
  * Nothing.
  */
  launch: function() {
    this.initPreferences();
    this.callback('onLoad');
  },
  
  /* Method: log
  
  Logs modules message in the console, if one exists and if the "<debugMode>" is true.
  It is compliant with Firebug, Safari and Opera.
  *Experimental - Testing*
  
  Parameters:
  * String - string: the string to display in the console.
  
  Returns:
  * Nothing.
  */
  log: function(string) {
    if (this.debugMode) UWA.log(string);
  },
  
  /* to document */
  onEdit: function() {
    
    if (this.prefsForm) {
      var form = this.prefsForm;
    } else {
      var prefsForm = new UWA.Controls.PrefsForm( { module: this } );
      var form = prefsForm.getContent();
    }
    
    this.elements['edit'].setContent(form);
    
    var infos = this.getInfos();
    if(infos) this.elements['edit'].addContent(infos);

    // Fire "ShowEdit" notification with HTMLDivElement "edit" as argument
    this.callback('onShowEdit', this.elements['edit']);

    this.elements['edit'].show();
  },
  
  /* to document */
  getInfos: function() {
    if(this.metas['author']) {
      var p = this.createElement('p');
      p.setStyle('padding', '10px');
      p.setStyle('text-align', 'right');
      if(this.metas['website']) {
        var content = 'Widget by <strong><a href="' + this.metas['website'] + '" rel="author">' + this.metas['author'] + '</a></strong>';
      } else {
        var content = 'Widget by <strong>' + this.metas['author'] + '</strong>';
      }
      if(this.metas['version']) {
        content += ' - version <strong>' + this.metas['version'] + '</strong>';
      }
      p.setHTML(content);
      return p;
    }
    return false;
  },
  
  /* to document */
  endEdit: function() {
    this.elements['edit'].hide();
    if (this.onRefresh) this.onRefresh();
    else if (this.onLoad) this.onLoad();
    this.callback('onHideEdit');
  },
  
  /* to document */
  setDebugMode: function(mode) {
    if (mode) this.debugMode = true; else this.debugMode = false;
  },
  
  /* deprecated */
  setInline: function(mode) {
    if (mode) this.inline = true; else this.inline = false;    
  },
  
  /* to document */
  setCSS: function(css) {
    UWA.Utils.setCss(this.id, css);
  },
  
  /* to document */
  openURL: function(url) {
    if (this.environment && this.environment.openURL) this.environment.openURL(url); 
    else window.open(url);
  }
 
}

// old name
UWA.Module = UWA.Widget;

/* Library: UWA Utils

Copyright:
  2006-2007 Netvibes. All rights reserved.

*/

if (typeof UWA == "undefined") var UWA = {};

UWA.Utils = {

  buildUrl: function (moduleUrl, linkHref) {
        var first_split = moduleUrl.split("://");
        var scheme =  first_split[0]
        var without_resource = first_split[1];
        var second_split = without_resource.split("/");
        var domain = second_split[0];
        var path = '';
        for (i=1;i<second_split.length-1;i++) {
            path += '/' + second_split[i];
        }
        if (linkHref.split("://").length > 1) { // complete
            return false;
        } else if (linkHref.substring(0, 1) == '/') { // absolute
            return scheme +'://' + domain + linkHref;
        } else { // relative
            return scheme +'://' + domain + path + '/' + linkHref;
        }
    },

  setTooltip: function(element, text, width) {
    if (window.App && App.toolTip)
      new App.toolTip(element, text, width, "left");
    return false;
  },

  setCss: function(id, content, namespace) {
    
    if (namespace == undefined) var namespace = '#m_' + id;
    
    var cssId = 'css_' + id;
    
    if (!$(cssId)) {
      var css = document.createElement("style");
      css.setAttribute('id', cssId);
      css.setAttribute('type','text/css');
      var head = document.getElementsByTagName('head').item(0);
      head.appendChild(css);
    } 
    
    content = content.replace(/#moduleContent/g, '');
    content = content.replace(/\n\s*([a-zA-z0-9\.\-, :#]*)\s*([{|,])/g, "\n" + namespace + " $1$2");
    
    if ($(cssId).styleSheet){ // IE
      $(cssId).styleSheet.cssText = content;
    } else { // w3c
      $(cssId).appendChild( document.createTextNode(content) );
    }
    
  },
  
  parseFeed: function(feed) {
    var is_xml = false, is_json = false;
    if (typeof feed.getResponseHeader == "function" || /* IE */ typeof feed.getResponseHeader == "unknown") {
    	if (feed.getResponseHeader("Content-type").substr(0, 8) == "text/xml") {
    		is_xml = true;
    	}
    } else if (typeof feed.responseJson == "object" && (feed.responseJson.nvFeed == 1 || feed.responseJson.error == 1)) {
    	is_json = true;
    } else {
    	if (feed.responseText.substr(0, 1) == "<") {
    		is_xml = true;
    	}
    }
    if (is_xml) {
    	newFeed = UWA.Utils.parseXmlFeed(feed);
    } else if (is_json) {
    	newFeed = feed.responseJson;
    } else if (feed.responseText != "") {
    	try {
    		newFeed =  eval('(' + feed.responseText + ')');
    	} catch (e) {
    	  UWA.log(e);
    		return false;
    	}
    } else {
    	return false;
    }
    delete feed;
    feed = null;
    var result = {};
    for (var i in newFeed) {
    	if (typeof newFeed.hasOwnProperty != "string" && !newFeed.hasOwnProperty(i)) continue;
    	result[i] = newFeed[i];
    }
    delete newFeed;
    newFeed = null;
    return result;
  },

  crc32: function(str, crc) { 
    if (typeof crc == "undefined") crc = 0;
    var table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D";
    var n = 0; // a number between 0 and 255
    var x = 0; // an hex number

    crc = crc ^ (-1);
    for (var i = 0, k = str.length; i < k; i++) {
      n = (crc ^ str.charCodeAt(i)) & 0xFF;
      x = "0x" + table.substr(n * 9, 8);
      crc = (crc >>> 8) ^ x;
    }
    return crc ^ (-1);
  },
  
  baseConvert: function(num, fromBase, toBase) {
    var b36arr = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j', 'k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
    var str = num.toString().toLowerCase();
    var p = 1;
    var b10 = 0;
    for(i = str.length - 1; i >= 0; i--) { 
      b = str.charCodeAt(i); 
      if (b >= 48 && b <= 57){ 
        b -= 48; 
      } else if (b >= 97 && b <= 122) { 
        b -= 97 - 10; 
      } 
      b10 += b * p; 
      p *= fromBase;
    } 
    var newval = ''; 
    var ost = 0; 
    while (b10 > 0) { 
      ost = b10 % toBase; 
      b10 = Math.floor(b10 / toBase); 
      newval = b36arr[ost] + '' + newval; 
    } 
    return newval; 
  },
  
  parseXmlFeed: function(feed) {
    var result = {};
    
  	if (feed.responseText == ''
		|| feed.responseXML.documentElement==null
		|| feed.responseXML.documentElement.nodeName=="parsererror") {
		result.error = true;
		return result;
	}

	var this_root = feed.responseXML.documentElement;
	result.type = (this_root.nodeName=="feed") ? 1 : 0;
	// htmlUrl
	var root = (result.type==1) ? this_root : this_root.getElementsByTagName("channel")[0];
	var link = UWA.Utils.getChildrenByTagName(root, "link");
	if (result.type==1) {
		for (var i = 0; i < link.length; i++) {
			if (link[i].getAttribute("type")=="text/html" || link.length==1) {
				result.htmlUrl = link[i].getAttribute("href");
			}
		}
	} else {
		result.htmlUrl = (link && link[0] && link[0].firstChild) ? link[0].firstChild.nodeValue : "";
	}

	// title
	var title = UWA.Utils.getChildrenByTagName(root, "title")[0];
	result.title = (title && title.firstChild) ? title.firstChild.nodeValue : result.htmlUrl;

	// description
	var desc = (result.type==1) ? this_root.getElementsByTagName("tagline") : this_root.getElementsByTagName("description");
	result.description = (desc && desc.length>0) ? ((desc[0].firstChild) ? desc[0].firstChild.nodeValue : '') : '';

	result.items = [];
	var items = (result.type==1) ? this_root.getElementsByTagName("entry") : this_root.getElementsByTagName("item");
	var ln = items.length;

	for (var i = 0; i < ln; i++) {
		var obj = {};

		obj_enclosures = [];
		var enclosures = items[i].getElementsByTagName("enclosure");
		for (var j = 0; j < enclosures.length; j++) {
			var checkType = enclosures[j].getAttribute("type");
			if (/audio/.test(checkType)) {
			} else if (/video/.test(checkType)) {
			} else if (/image/.test(checkType)) {
			} else {
				continue;
			}
			var url = enclosures[j].getAttribute("url");

			if (checkType == "") {
				if (strpos(url, ".mp3") !== false) {
					checkType = "audio/mpeg";
				}
			}
			if (checkType == "") continue;

			obj_enclosures.push({"type": checkType, "url": url});
		}
		if (obj_enclosures.length > 0) {
			obj.enclosures = obj_enclosures;
		}

		var title = UWA.Utils.getChildrenByTagName(items[i], 'title')[0];
		if (title && title.firstChild) {
		    if (title.firstChild.nextSibling) obj.title = title.firstChild.nextSibling.nodeValue; // Handle CDATA
		    else obj.title = title.firstChild.nodeValue;
		} else {
			var d = items[i].getElementsByTagName("description");
			if (d[0] && d[0].firstChild) {
				var tmp = document.createElement("div");
				tmp.innerHTML = d[0].firstChild.nodeValue;
				obj.title = ((tmp.innerText)?tmp.innerText.substring(0,50).stripTags():'')+"...";
			} else {
				obj.title = '[...]';
			}
		}

		var dcDate = (UWA.Client.Engine.ie) ? items[i].getElementsByTagName("dc:date")[0] : items[i].getElementsByTagName("date")[0];
		if (items[i].getElementsByTagName("pubDate")[0]) {
			obj.date = (items[i].getElementsByTagName("pubDate")[0].firstChild) ? items[i].getElementsByTagName("pubDate")[0].firstChild.nodeValue : "";
		} else if (dcDate) {
			obj.date = dcDate.firstChild.nodeValue;
		} else if (items[i].getElementsByTagName("issued")[0]) {
			obj.date = items[i].getElementsByTagName("issued")[0].firstChild.nodeValue;
		}

		// for <media:thumbnail> enclosures type. See http://search.yahoo.com/mrss 
		var mediaThumbnail = (UWA.Client.Engine.ie) ? items[i].getElementsByTagName("media:thumbnail")[0] : items[i].getElementsByTagName("thumbnail")[0];
		if(mediaThumbnail){
			obj.thumbnail = mediaThumbnail.getAttribute('url');
		}

		var link = UWA.Utils.getChildrenByTagName(items[i], "link");
		if (link.length>0) {
			if (result.type==1) {
				for (var j = 0; j < link.length; j++) {
					if (link[j].getAttribute("type")=="text/html" || link.length==1) {
						obj.link = link[j].getAttribute("href");
					}
				}
			} else {
				if (link[0] || link[0].firstChild) {
					obj.link = (link[0].firstChild) ? link[0].firstChild.nodeValue : '';
				}
			}
		} else if (result.type == 0) {
			if (items[i].getElementsByTagName("guid").length > 0 && items[i].getElementsByTagName("guid")[0].firstChild) {
				obj.link = items[i].getElementsByTagName("guid")[0].firstChild.nodeValue;
			}
		}

		if (!obj.link) {
			obj.link = result.htmlUrl;
		}

		if (obj.link!="" && obj.link!=result.htmlUrl) {
			var str = obj.link;
		} else {
			var str = obj.title+obj.date+obj.link;
		}
		obj.id_old = str.replace(/([^0-9a-zA-Z])/g,"");
		obj.id = this.baseConvert(this.crc32(obj.id_old), 16, 36);
	
		// Use the guid as id if it exists
		var guidList = items[i].getElementsByTagName("guid");
		if (guidList.length > 0) {
			var guidValue = guidList[0].firstChild.nodeValue;
			obj.id = guidValue.replace(/([^0-9a-zA-Z])/g,"");;
		}

		if (result.type==1) {
			var content = items[i].getElementsByTagName("content")[0];
			var desc = items[i].getElementsByTagName("summary")[0];
		} else {
			var content = (UWA.Client.Engine.ie) ? items[i].getElementsByTagName("content:encoded")[0] : items[i].getElementsByTagName("encoded")[0];
			var desc = items[i].getElementsByTagName("description")[0];
		}

		// here find a way to fix content with IE and feeds like "http://googleblog.blogspot.com/atom.xml" that doesn't have all the content encoded
		contentValue = "";

		if (content && content.hasChildNodes()) {
			for (var n = content.firstChild; n != null; n = n.nextSibling) {
				if (n.innerHTML) {
					contentValue += n.innerHTML;
				} else if (n.nodeValue) {
					contentValue += n.nodeValue;
				}
			}
		} else if (desc && desc.hasChildNodes()) {
			for (var n = desc.firstChild; n != null; n = n.nextSibling) {
				if (n.innerHTML) {
					contentValue += n.innerHTML;
				} else if (n.nodeValue) {
					contentValue += n.nodeValue;
				}
			}
		}

		obj.content = contentValue;

		result.items.push(obj);
	}
	return result;
  },
  
  getChildrenByTagName: function(node, tagName) {
  	var ln = (node && node.childNodes) ? node.childNodes.length : 0;
  	var arr = [];
  	for (var z=0; z<ln; z++) {
  		if (node.childNodes[z].nodeName==tagName) arr.push(node.childNodes[z]);
  	}
  	return arr;
  }
  
}

var Feed = function(feed, url) {
    return UWA.Utils.parseFeed(feed);
}

if (typeof Utils == "undefined") Utils = {};
Utils.getChildrenByTagName = UWA.Utils.getChildrenByTagName;

/* Library: UWA Data

_Copyright 2006-2007 Netvibes. All rights reserved._

*/

if (typeof UWA == "undefined") var UWA = {};

if (typeof UWA.proxies == "undefined") {
  
  UWA.proxies = {
    'api'  : NV_PATH + 'proxy/api2Proxy.php',
    'rss'  : NV_PATH + 'proxy/xmlProxy.php',
    'ajax' : NV_PATH + 'proxy/ajaxProxy.php',
    'feed' : NV_PATH + 'proxy/feedProxy.php',
    'xml'  : NV_PATH + 'data/xml/'
  }
  
}


if (typeof UWA.Json == "undefined") UWA.Json = {};

  /* Method: request

  Builds a "JSON" request, by creating a temporary Javascript tag to access the URL.

  Parameters:
  * String - url: the URL of the data source,
  * Collection{Object} - request: an Object collection representing a request (proxy and callback keys).

  Returns:
  * Nothing,

  Example:
  (start code)
  ...
  UWA.Json.request(url, { callback: callback } );
  ...
  (end)
  This method is used by the <UWA.Data> class. In Modules, you usually use the <UWA.Data> class.
  */  

UWA.Json.request = function(url, request) {

  var varname = 'json';
  
  if (request.context && request.context[0]) varname += request.context[0];
  else varname += Math.round(1000*1000*Math.random());

  eval(varname + '= false');

  url += '&object=' + varname ;

  var script = document.createElement('script');
  script.setAttribute('type', 'text/javascript');
  script.src = url;
  var head = document.getElementsByTagName('head')[0];
  var insert = head.appendChild(script);

  if (typeof request.onComplete == "undefined") UWA.log('no callback set');

  var callback = request.onComplete;

  var myCallback = function(c){ return function(j) { callback(j, c) } }(request.context);

  var interval = setInterval( ( function() {
    eval('var json = ' + varname);
    if (json) {
      try {
        myCallback(json);
      } catch(e) {
        UWA.log(e);
      }
      insert.parentNode.removeChild(insert);
      clearInterval(interval);
    }
  } ).bind(this), 100);

}

UWA.Data = {
  
  useJsonRequest: false,
  
  /* Method: getFeed

  This method is used to get the content of a feed, in a JSON format.

  Parameters:
  * String - url: the URL of the feed data source,
  * Function - callback: the callback method that will be fired when the request is succesful. 
  This method *must have one parameter* to receive the feed (JSON format) returned by the request.

  Returns:
  * Nothing, but the callback method is fired if the request is successful, and receives the feed as parameter.
  
  Example:
  (start code)
  ...
  UWA.Data.getFeed(this.getValue('http://feeds.feedburner.com/NetvibesDevBlog'), myModule.display.bind(this));
  ...
  myModule.display = function(aFeed) {
  ... 
  }
  ...
  (end)
  In this example, the callback method is named "display", and is used to display the feed content.
  *Please note the ".bind(this)" usage when providing a callback method.*
  */
  getFeed: function(url, callback) {
    if (typeof UWA.feedCallbackType == "undefined") UWA.feedCallbackType = "json";
    return this.request(url, { method : 'GET', proxy: 'feed', type: UWA.feedCallbackType, onComplete: callback } );
  },

  /* Method: getXml

  This method is used to get the content of an external XML data source. 
  It can be used to retrieve the content of a feed in XML format.

  Parameters:
  * String - url: the URL of the feed data source,
  * Function - callback: the callback method that will be fired when the request is succesful. 
  This method *must have one parameter* to receive the XML content returned by the request.

  Returns:
  * Nothing, but the callback method is fired if the request is successful, and receives the XML content as parameter.
  
  Example:
  (start code)
  ...
  UWA.Data.getXml("http://digg.com/rss/index.xml", myModule.parse.bind(this));
  ...
  myModule.parse = function( xml) {
  ...
  }
  (end)
  */ 
  getXml: function(url, callback) {
    return this.request(url, { method : 'GET', proxy: 'ajax', type: 'xml', onComplete: callback } );
  },
  
  /* to document */
  getText: function(url, callback) {
    return this.request(url, { method : 'GET', proxy: 'ajax', type: 'text', onComplete: callback } );
  },
  
  /* to document */
  getJson: function(url, callback) {
    return this.request(url, { method : 'GET', proxy: 'ajax', type: 'json', onComplete: callback } );
  },

  /* Method: getModule

  This method is used to get the content of an external module, in XML format.

  Parameters:
  * String - url: the URL of the feed data source,
  * Function - callback: the callback method that will be fired when the request is succesful. 
  This method *must have one parameter* to receive the module content returned by the request.

  Returns:
  * Nothing, but the callback method is fired if the request is successful, and receives the module content as parameter.
  */  
  getModule: function(url, callback, id) {
    if (UWA.proxies['api']) {
      url = UWA.proxies['api'] + '?moduleUrl=' + encodeURIComponent(url);
      if (id) url += '&moduleId=' + id;
      return this.request(url, { method : 'GET', type: 'xml', onComplete: callback } );
    }
    UWA.log('no proxy URL set for module'); return false;
  },

  /* to document */
  request: function(url, request) {
    
    if (typeof request == 'undefined') request = {};
    
    if (typeof request.method == 'undefined') request.method = 'GET';

    if (request.method == 'DELETE' || request.method == 'PUT') {
      // TODO: Restrict this patch to Opera and Safari
      if (typeof request.headers  == 'undefined') request.headers = {};
      request.headers['X-Requested-Method'] = request.method;
      request.method = 'POST';
    }

    if (typeof request.proxy == 'undefined') {
      if (url.substr(0, 4) == "http" && url.indexOf("http://" + location.hostname) == -1 ) request.proxy = 'ajax';
    }
    
    if (typeof request.type == 'undefined') request.type = 'text';
    
    if (UWA.proxies[request.proxy]) {
      url = UWA.proxies[request.proxy] + '?url=' + encodeURIComponent(url);
      if (request.proxy == "feed" && request.shortFeed != false) url += "&rss=1";
    } else if (request.proxy) {
      UWA.log('no proxy URL set for ' + request.proxy);
    }
    
    if (typeof request.authentication == 'object') {
      if (request.authentication.type) url += '&auth=' + request.authentication.type;
      if (request.authentication.moduleId) url += '&moduleId=' + request.authentication.moduleId;
      if (request.authentication.username) url += '&username=' + encodeURIComponent(request.authentication.username);
      if (request.authentication.password) url += '&password=' + encodeURIComponent(request.authentication.password);
      if (request.authentication.gp) url += '&gp=' + request.authentication.gp;
    }
      
    if (request.type && request.proxy) {
      url += '&type=' + request.type;
    }
    
    if (request.cache) {
      url += '&cache=' + request.cache;
    }
    
    if(UWA.Client.Engine.ie) {
      url += '&rnd='+ Math.random();
    }
    
    switch(request.type) {
      
      case 'json':
        if (this.useJsonRequest && typeof request.authentication == "undefined") {
          return UWA.Json.request(url, request);
        } else {
          var callback = request.onComplete;
          var context = request.context;
          request.onComplete = function() {
            UWA.Ajax.onCompleteJson(arguments, callback, context);
          }
          return UWA.Ajax.Request(url, request);
        }
      
      case 'xml':
        var callback = request.onComplete;
        request.onComplete = function() {
          UWA.Ajax.onCompleteXML(arguments, callback);
        }
        return UWA.Ajax.Request(url, request);
      
      case 'feed':
        var callback = request.onComplete;
        request.onComplete = function() {
          UWA.Ajax.onCompleteFeed(arguments, callback, context);
        }
        return UWA.Ajax.Request(url, request);
      
      default:
      case 'text':
      case 'html':
        var callback = request.onComplete;
        var context = request.context;
        request.onComplete = function() {
          UWA.Ajax.onCompleteText(arguments, callback, context);
        }
        return UWA.Ajax.Request(url, request);
    }
    
  },

  /* function here for compatibility :
	used in Dashboard	when the user clicks on 'OK' in preferences */

  saveDatas: function(moduleId, datas, callback) {
    var params = '';
    for (var key in datas) {
        if (datas[key] == null || typeof datas[key] == 'function' || datas[key] == 'lastUpdate') continue;
        if (params != '') params += '&';
        params += 'data[' + key + ']=' + encodeURIComponent(datas[key]);
    }
    var requestUrl = NV_PATH + 'data/save.php?id=' + moduleId;
    var request = { method: 'post', parameters: params };
    if (typeof callback == "function") request.onComplete = callback;
    this.request(requestUrl, request);
  }
  
};

/* Class: UWA.Environment

The Environment Base class provide base functions to run a Module Execution Environnement.
It is an abstract class, and must be extended to be useful.
The object must be filled with DOM elements (at least body), in the "<onInit>" or "<onRegisterModule>" callbacks for example.

_Copyright 2006-2007 Netvibes. All rights reserved._
*/

if (typeof UWA == "undefined") var UWA = {};

UWA.Environment = function() {

    /* Property: module

    *Module*: current module registered in this environnement.
    */
    this.module = false;
    
    this.widget = this.module;
    
    /* Property: html

    *String*: HTML Dom elements of this environnement
    */
    this.html = {};
     
    /* Property: loaded

    *Boolean*: flag to know if the Environnement is ready.
    */
    this.loaded = false;
  
    /* Property: registered

    *Boolean*: flag to know if the Module is registered.
    */
    this.registered = false;
    
    /* Property: callbacks 

    *Collection{Function}*: _experimental_ collection of callback methods.
    */
    this.callbacks = {};

    /* Property: query

    *String*: _experimental_ query string.
    */
    this.query = ''; // where is it used ?

    /* Property: data

    *Collection{Object}*: _experimental_ data.
    */
    this.data = {};

    /* Property: debugMode

    *Boolean*: activates (or not) the debug mode (display message in console).
    */    
    this.debugMode = false;
    
    /* Property: periodicals

    *Collection{Object}*: store periodicals events
    */
    this.periodicals = {};
    
    /* Property: delays

    *Collection{Object}*: store delayed events
    */
    this.delays = {};
    
    /* to document */
    this.height = 200;
    
    if(this.initialize) this.initialize();
    
    this.setPeriodical('init', this.init, 100, true);

}

UWA.Environment.prototype = {
  
  /* Method: init

  Initialize the Environment, when DOM is ready

  Parameters:
  * None.

  Returns:
  * Nothing.
  */ 
  init: function() {
    if (document.body) {
      this.callback('onInit');
      this.clearPeriodical('init');
      this.log('Environnement loaded');
      this.loaded = true;
      return true;
    }
    return false;
  },

  /* Method: getModule

  Returns the module currently registered in the Environment. 
  If no module is registered, the Environment creates one and registers it.

  Parameters:
  * None.

  Returns:
  * Module: the (maybe newly created) registered module.
  */ 
  getModule: function() {
    if (this.module) {
      var module = this.module;
    } else {
      var module = new UWA.Module();
      this.registerModule(module);
    }
    return module;
  },
  
  /* Method: registerModule

  Registers a Module into the execution Environment (tries to "<launch _register>" until the Environment is ready).

  Parameters:
  * Module : the module to register in the Environment.

  Returns:
  * Nothing.
  */ 
  registerModule: function(module) {
    this.module = module;
    this.widget = this.module;
    module.environment = this;
    this.setPeriodical('register', function() {
      if (this.loaded) {
        this.callback('onRegisterModule');
        this.registered = true;
        this.log('Module registered');
        this.clearPeriodical('register');
      }
    }, 100, true);
  },

  /* Method: launchModule

  Launches the registered module, or the module given as a parameter

  Parameters:
  * Module - module: (optional) to launch another module than the registered module.

  Returns:
  * Nothing.
  */
  launchModule: function() {
    this.setPeriodical('launch', function() {
      if (this.loaded && this.module && this.registered) {
          this.log('Launching module');
          this.module.launch();
          this.clearPeriodical('launch');
          if (this.query && this.query != '' && this.module.onSearch) {
              this.module.onSearch(this.query); // to move in a callback ? seems used in frame env ...
          } 
      }
    }, 100, true);
  },
  
  /* Method: setCallback

  Stores an association of callback function with the name of the event that fires them.

  Parameters:
  * String - name: name of the event,
  * Function - fn: the callback function to fire for the event.

  Returns:
  * Nothing.
  */
  setCallback: function(name, fn) {
    this.callbacks[name] = fn;
  },
  
  /* to document */
  callback: function(name, args, bind) {
    if (typeof bind == 'undefined') bind = this;
    try {
      if (this[name]) return this[name].apply(bind, [args]);
      if (this.callbacks[name]) return this.callbacks[name].apply(bind, [args]);
    } catch(e) {
      this.log(e);
    }
    return false;
  },
 
  /* to document */
  setPeriodical: function(name, fn, delay, force) {
    this.clearPeriodical(name);
    fn = fn.bind(this);
    this.periodicals[name] = setInterval(fn, delay);
    if (force) fn();
  },
  
  /* to document */
  clearPeriodical: function(name) {
    if (this.periodicals[name]) { clearInterval(this.periodicals[name]) }
  },
  
  /* to document */
  setDelayed: function(name, fn, delay, bind) {
    this.clearDelayed(name);
    if(typeof bind == "undefined" || bind === true) fn = fn.bind(this);
    this.delays[name] = setTimeout(fn, delay);
  },
  
  /* to document */
  clearDelayed: function(name) {
    if (this.delays[name]) { clearTimeout(this.delays[name]) }
  },
  
  /* to document */
  setIcon: function(url) {
    if(this.module.elements['icon']) this.module.elements['icon'].setHTML('<img width="16" height="16" src="' + url + '" />');
  },
   
  /* Method: log

  If <debugMode> is TRUE, writes log messages in the console. Compatible with Firebug, Safari, Opera...

  Parameters:
  * Strig - string: the string to display.

  Returns:
  * Nothing.
  */
  log: function(string) {
    if (this.debugMode) UWA.log(string);
  }

}


/*
Script: Services/Search.js

Copyright 2005-2007 Netvibes Ltd.
All rights reserved.
*/

if (typeof UWA == "undefined") var UWA = {};
if (typeof UWA.Services == "undefined") UWA.Services = {};
if (typeof UWA.Services.Search == "undefined") UWA.Services.Search = {};

UWA.Services.Search.getFromProvider = function(provider, request) {

   var options = "";

   if (typeof request.lang != 'undefined') {
       options += "&lang=" + request.lang;
   }
   if (typeof request.locale != 'undefined') {
       options += "&locale=" + request.locale;
   }
   if (typeof request.mode != 'undefined') {
       options += "&mode=" + request.mode;
   }

   switch (request.type) {
       case "websearch":
           var url = NV_PATH + 'data/websearch/' + '?q=' + encodeURIComponent(request.query) + '&engine=' + encodeURIComponent(provider) + options;
           return UWA.Data.request(url, { method : 'GET', type: 'json', onComplete: request.onComplete, context : request.context } );

       case "blogsearch":
           var url = NV_PATH + 'data/blogsearch/' + '?q=' + encodeURIComponent(request.query) + '&engine=' + encodeURIComponent(provider) + options;
           return UWA.Data.request(url, { method : 'GET', type: 'json', onComplete: request.onComplete, context : request.context } );

       case "imagesearch":
           var url = NV_PATH + 'data/imagesearch/' + '?q=' + encodeURIComponent(request.query) + '&engine=' + encodeURIComponent(provider) + options;
           return UWA.Data.request(url, { method : 'GET', type: 'json', onComplete: request.onComplete, context : request.context } );

       case "videosearch":
           var url = NV_PATH + 'data/videosearch/' + '?q=' + encodeURIComponent(request.query) + '&engine=' + encodeURIComponent(provider) + options;
           return UWA.Data.request(url, { method : 'GET', type: 'json', onComplete: request.onComplete, context : request.context } );

       case "podcastsearch":
           var url = NV_PATH + 'data/podcastsearch/' + '?q=' + encodeURIComponent(request.query) + '&engine=' + encodeURIComponent(provider) + options;
           return UWA.Data.request(url, { method : 'GET', type: 'json', onComplete: request.onComplete, context : request.context } );

       case "shoppingsearch":
           var url = NV_PATH + 'data/shoppingsearch/' + '?q=' + encodeURIComponent(request.query) + '&engine=' + encodeURIComponent(provider) + options;
           return UWA.Data.request(url, { method : 'GET', type: 'json', onComplete: request.onComplete, context : request.context } );

       case "opensearch":
           var url = NV_PATH + 'data/opensearch/' + '?q=' + encodeURIComponent(request.query) + '&url=' + encodeURIComponent(request.url) + options;
           return this.request(url, { method : 'GET', type: 'json', onComplete: request.onComplete, context : request.context } );

       default:
           UWA.log('invalid request type'); 
           break;
    }
}

// Retro-compatibility
UWA.Data.getFromProvider = UWA.Services.Search.getFromProvider

/*
Copyright 2005-2007 Netvibes Ltd
All rights reserved.
Author : Jérémy Bethmont
*/

UWA.Services.FeedHistory = {};

UWA.Services.FeedHistory.build = function(historyData, feedObj) {
	return App.Rss.buildHistory(historyData, feedObj);
	
	if (feedObj.history) {
		if (feedObj.history.lastPostId) {
			UWA.Services.FeedHistory.upgrade(feedObj);
		}
	} else {
		feedObj.history = {};
		if (historyData && historyData != "") {
			var arr = historyData.split(":");
			if (arr[arr.length-1] == 1 || arr[arr.length-1] == 0) {
				// old style
				feedObj.history.lastPostId = arr[0];
				arr.splice(0,1);
				feedObj.history.postStatus = arr;
				UWA.Services.FeedHistory.upgrade(feedObj);
			} else {
				var ln = feedObj.items.length;
				for (var z = 0, ln = arr.length; z < ln; z++) {
					feedObj.history[arr[z]] = true;
				}
			}
		}
	}
	UWA.Services.FeedHistory.cleanup(feedObj);
};

UWA.Services.FeedHistory.cleanup = function(feedObj) {
	var newHistory = {};
	
	var ln = feedObj.items.length;
	for (var z = 0; z < ln; z++) {
		if (feedObj.history[feedObj.items[z].id]) {
			newHistory[feedObj.items[z].id] = feedObj.history[feedObj.items[z].id];
			continue;
		}
		if (feedObj.history[feedObj.items[z].id_old]) {
			newHistory[feedObj.items[z].id] = feedObj.history[feedObj.items[z].id_old];
			continue;
		}
	}
	feedObj.history = newHistory;
};

UWA.Services.FeedHistory.upgrade = function(feedObj) {
	if (!feedObj.history.lastPostId) return false;
	
	if (feedObj.history.lastPostId == feedObj.items[0].id || feedObj.history.lastPostId == feedObj.items[0].id_old) {
		var oldHistory = feedObj.history.postStatus.slice(); // copy
	} else {
		var newArr = [];
		var ln = feedObj.items.length;
		var lastPos;
		for (var z = 0; z < ln; z++) {
			if (feedObj.history.lastPostId == feedObj.items[z].id || feedObj.history.lastPostId == feedObj.items[z].id_old) {
				lastPos = z;
				break;
			}
		}
		for (var z = 0; z < ln; z++) {
			if (z < lastPos || !lastPos) {
				newArr[z] = 0;
			} else {
				newArr[z] = feedObj.history.postStatus[z - lastPos];
			}
		}
		var oldHistory = newArr;
	}
	
	feedObj.history = {};
	var ln = feedObj.items.length;
	for (var z = 0; z < ln; z++) {
		if (oldHistory[z] == 1) {
			feedObj.history[feedObj.items[z].id] = true;
		}
	}
	
};

UWA.Services.FeedHistory.getString = function(feedObj) {
	return App.Rss.getHistoryString(feedObj);
	
	if (!feedObj.history) return "";
	var history = "";
	var t = "";
	for (var i in feedObj.history) {
		if (!feedObj.history[i]) continue;
		history += t + i;
		t = ":";
	}
	return history;
};

UWA.Services.FeedHistory.getNbNew = function(feedObj, limit) {
	return App.Rss.getHistoryNbNew(feedObj, limit);
	
	if (!feedObj || !feedObj.history) return 0;
	var ln = feedObj.items.length;
	var n = 0;
	
	for (var z = 0; z < limit; z++) {
		if (!feedObj.history[feedObj.items[z].id]) {
			n += 1;
		}
	}
	return n;
};

UWA.Services.FeedHistory.setRead = function(feedObj, index) {
	if (typeof feedObj.history == "undefined") return ;
	
	return feedObj.history.postStatus[index] = 1;
	
	feedObj.history[feedObj.items[index].id] = true;
};

UWA.Services.FeedHistory.setUnRead = function(feedObj, index) {
	if (typeof feedObj.history == "undefined") return ;
	
	return feedObj.history.postStatus[index] = 0;
	
	delete feedObj.history[feedObj.items[index].id];
};

UWA.Services.FeedHistory.isRead = function(feedObj, index) {
	return feedObj.history.postStatus[index] == 1;
	
	if (feedObj.history[feedObj.items[index].id]) return true;
	return false;
};

if (typeof App == "undefined") App = {};
if (typeof App.Rss == "undefined") App.Rss = {};

// reverted to the old behavior
App.Rss.buildHistory = function(historyData, feedObj) {
	if (feedObj.history) {
		App.Rss.updateHistory(feedObj);
	} else {
		feedObj.history = {};
		if (historyData=="" || historyData==null) {
			var arr = [];
			var ln = feedObj.items.length;
			for (var z=0; z<ln; z++) arr[z] = 0;
			feedObj.history = {lastPostId:feedObj.items[0].id, postStatus:arr};
		} else {
			var arr = historyData.split(":");
			feedObj.history.lastPostId = arr[0];
			arr.splice(0,1);
			feedObj.history.postStatus = arr;
			App.Rss.updateHistory(feedObj);
		}
	}
};
App.Rss.updateHistory = function(feedObj) {
	if (feedObj.history.lastPostId==feedObj.items[0].id || feedObj.history.lastPostId==feedObj.items[0].id_old) {
		feedObj.history = {lastPostId:feedObj.items[0].id, postStatus:feedObj.history.postStatus};
	} else {
		var newArr = [];
		var ln = feedObj.items.length;
		var lastPos;
		for (var z=0; z<ln; z++) {
			if (feedObj.history.lastPostId==feedObj.items[z].id || feedObj.history.lastPostId==feedObj.items[z].id_old) {
				lastPos = z;
				break;
			}
		}
		for (var z=0; z<ln; z++) {
			if (z<lastPos || !lastPos) {
				newArr[z] = 0;
			} else {
				newArr[z] = feedObj.history.postStatus[z-lastPos];
			}
		}
		feedObj.history = {lastPostId:feedObj.items[0].id, postStatus:newArr};
	}
};
App.Rss.getHistoryString = function(feedObj) {
	if (!feedObj.history) return "";
	return feedObj.history.lastPostId+":"+feedObj.history.postStatus.join(":");
};
App.Rss.getHistoryNbNew = function(feedObj, limit) {
	if (!feedObj || !feedObj.history) return 0;
	var ln = feedObj.history.postStatus;
	var n=0;
	for (var z=0; z<limit; z++) {
		if (feedObj.history.postStatus[z]!=1) n++;
	}
	return n;
};

/* Class: UWA.Environments.Standalone

_Copyright 2006-2007 Netvibes. All rights reserved._

*/

Object.extend(UWA.Environment.prototype, {
  
initialize: function() {
  this.standalone = {};
},

onInit: function() {

  // creating module header
  var moduleHeader = document.createElement('div');
  moduleHeader.setAttribute('id','moduleHeader');
  moduleHeader.className = 'moduleHeader';
  moduleHeader.innerHTML = 
      '<div class="edit"><a href="#">Edit</a></div>' +
      //'<div class="refresh"><img src="http://www.netvibes.com/api/0.3/refresh.gif"></div>' +
      '<div class="ico" id="moduleIcon" style="padding-left:3px">&nbsp;</div>' +
      '<div id="moduleTitle" class="title">' + document.title + '</div>';
  
  // creating module content
  var moduleContent = document.createElement('div');
  moduleContent.setAttribute('id','moduleContent');
  moduleContent.className = 'moduleContent';
  moduleContent.innerHTML = document.body.innerHTML ;
  
  // creating edit content
  var editContent = document.createElement('div');
  editContent.setAttribute('id','editContent');
  editContent.style.display = 'none';
  editContent.className = 'editContent optionContent configureContent';
  
  document.body.innerHTML = '';
  
  var wrapper = document.createElement('div');
  wrapper.setAttribute('id','wrapper');

  this.html['header'] = wrapper.appendChild(moduleHeader);
  this.html['edit'] = wrapper.appendChild(editContent);
  this.html['body'] = wrapper.appendChild(moduleContent);

  document.body.appendChild(wrapper);
  
  this.html['title'] = document.getElementById('moduleTitle'); // to refactor
  this.html['icon'] = document.getElementById('moduleIcon'); // to refactor
  
  var addto = document.createElement('div');
  addto.setAttribute('id','addto');
  
  addto.innerHTML =  '<a style="border:0" title="Add this module to Netvibes" href="' + NV_PATH + 'subscribe.php?module=UWA&amp;moduleUrl=' + encodeURIComponent(document.location.href) + '"><img alt="Add to Netvibes" src="' + NV_PATH + 'img/uwa-netvibes.png" /></a>';
  
  addto.innerHTML +=  '<br /> <br /><a style="border:0" title="Add this module to Google Homepage" href="http://www.google.com/ig/add?moduleurl=' + encodeURIComponent(NV_PATH + 'api/uwa/compile/google.php?moduleUrl=' +  encodeURIComponent(document.location.href) ) + '"><img alt="Add to Google Homepage" src="' + NV_PATH + 'img/uwa-google.png" /></a>';

  document.body.appendChild(addto);
    
},

onRegisterModule: function() {
  
  for (var key in this.html) {
    this.module.elements[key] = UWA.$element(this.html[key]);
  }
  
  // new syntax
  this.module.body = this.module.elements['body'];
  
  var editLink = this.module.elements['header'].getElementsByClassName('edit')[0];
  editLink.onclick = ( function() {
    if (this.elements['edit'].style.display == 'none') {
      this.callback('onEdit');
    } else {
      this.elements['edit'].hide();
    }
    return false;
  } ).bindAsEventListener(this.module);
  
  /*
  var refreshLink = this.$('header').getElementsByClassName('refresh')[0];
  refreshLink.onclick = ( function() {
    this.callback('onRefresh')
  } ).bindAsEventListener(this.module);
  */
  
  var xmlMetas = document.getElementsByTagName("meta");
  if(xmlMetas && xmlMetas.length) this.module.setMetasXML(xmlMetas);
  
  var xmlPrefs = document.getElementsByTagName("preference");
  if (xmlPrefs && xmlPrefs.length) this.module.setPreferencesXML(xmlPrefs);
  
  var links = document.getElementsByTagName('link');
  for(var i = 0; i < links.length; i++) {
    if(links[i].getAttribute('rel') == 'icon') {
      var favicon = links[i].getAttribute('href');
    }
  }
  if(favicon) {
    // var buildHref = UWA.Utils.buildUrl(this.widget.getValue('moduleUrl'), favicon);
    // if(buildHref) { favicon = buildHref }
    this.setIcon(favicon);
  }
    
  var launchModule = setTimeout(this.launchModule.bind(this), 100);
     
},

showEdit: function() {
  if(this.module.onEdit) this.module.onEdit();
},

getData: function(name) {
  if(window.Cookie) return Cookie.get('uwa-' + name);
},

setData: function(name, value) {
  if(window.Cookie) return Cookie.set('uwa-' + name, value);
}

});

var Environment = new UWA.Environment();

var widget = Environment.getModule();

UWA.Data.useJsonRequest = true;

function _(s) {
  return s
}

window.onresize = function() {
  widget.callback('onResize');
}

UWA.proxies['feed'] = NV_PATH + 'data/feed/';

function _(s) { return s };